如何使用ASP.NET Core MVC内置依赖注入框架手动解析类型?
设置容器很容易:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddTransient<ISomeService, SomeConcreteService>();
}
Run Code Online (Sandbox Code Playgroud)
但是如何在ISomeService不进行注射的情况下解决?例如,我想这样做:
ISomeService service = services.Resolve<ISomeService>();
Run Code Online (Sandbox Code Playgroud)
没有这样的方法IServiceCollection.
我是EF核心的新手,我正试图让它与我的asp.net核心项目一起工作.
startup.cs在尝试配置dbcontext以使用来自config的连接字符串时,我得到了上述错误.我正在关注本教程:https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro
startup.cs中有问题的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using tracV2.models;
using tracV2.data;
namespace tracV2
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton<IConfiguration>(Configuration);
string conn = Configuration.GetConnectionString("optimumDB");
services.AddDbContext<tracContext>(options => options.usesqlserver(conn));
}
Run Code Online (Sandbox Code Playgroud)
usesqlserver如果我将其直接放入上下文中,则会识别该方法:
using System; …Run Code Online (Sandbox Code Playgroud) 是否可以让我的ASP Core Web API确保使用EF Core将数据库迁移到最新的迁移?我知道这可以通过命令行完成,但我想以编程方式完成.
更新
根据Janshair Khan的回答,我提出了这个助手类:
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MyWebApi.Models;
namespace MyWebApi
{
public static class DataSeeder
{
public static void SeedData(this IApplicationBuilder app)
{
var context = app.ApplicationServices.GetService<MyContext>();
if (!context.Database.EnsureCreated())
context.Database.Migrate();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过以下Configure方法调用此方法Startup.cs:
app.SeedData();
Run Code Online (Sandbox Code Playgroud) 似乎在Entity Framework 7中还没有对种子数据的原生支持(https://github.com/aspnet/EntityFramework/issues/629).
Microsoft提供的模板代码中没有DbMigrationsConfiguration类,没有Seed方法.
那么如何在使用Entity Framework 7 RC 1的ASP.NET MVC 6 Web应用程序中播种数据呢?
c# entity-framework seeding entity-framework-core asp.net-core-mvc
如何从代码中应用迁移
对于EF6工作代码
Database.SetInitializer<CmContext>(null);
var settings = new MigrationsConfiguration();
var migrator = new DbMigrator(settings);
migrator.Update();
Run Code Online (Sandbox Code Playgroud)
如何在EF Core中制作类似的?
我正在使用 ASP.NET Core 6 编写一个网站。它最初是来自 YouTube 的 .NET Core 3 教程。所以我面临迁移问题。\n这里,我有一个 DbInitializer 文件,其中包含我的所有数据(即:我的数据库)。
\nusing DrinkAndGo.Data.Models;\nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.Extensions.DependencyInjection;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace DrinkAndGo.Data\n{\npublic class DbInitializer\n{\n public static void Seed(IApplicationBuilder applicationBuilder)\n {\n AppDbContext context =\n applicationBuilder.ApplicationServices.GetRequiredService<AppDbContext>();\n\n if (!context.Categories.Any())\n {\n context.Categories.AddRange(Categories.Select(c => c.Value));\n }\n\n if (!context.Drinks.Any())\n {\n context.AddRange\n (\n new Drink\n {\n Name = "Beer",\n Price = 7.95M,\n \n Category = Categories["Alcoholic"],\n ImageUrl = "http://imgh.us/beerL_2.jpg",\n InStock = true,\n IsPreferredDrink = true,\n ImageThumbnailUrl = "http://imgh.us/beerS_1.jpeg"\n },\n new Drink\n {\n Name = "Rum & Coke",\n Price …Run Code Online (Sandbox Code Playgroud) 对于EF6,我可以通过以下方式检查数据库是否存在:
context.Database.Exists()
Run Code Online (Sandbox Code Playgroud)
我怎么能在EF Core中这样做?
在.NET 5 Web应用程序中,我们在startup.cs中使用如下代码来使用实体框架初始化数据库:
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();
}
Run Code Online (Sandbox Code Playgroud)
但在 .NET 6 中,我收到没有 ApplicationServices 的错误。我尝试了此处提出的解决方案,但随后出现运行时错误:“无法从根提供程序解析作用域服务‘WebApplication1.DataAccess.SchoolDbContext’”。我的program.cs中的完整代码如下:
using WebApplication1.DataAccess;
using Microsoft.EntityFrameworkCore;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json");
builder.Services.AddRazorPages();
// Setup EF connection
// /sf/answers/3016870671/
// https://medium.com/executeautomation/asp-net-core-6-0-minimal-api-with-entity-framework-core-69d0c13ba9ab
builder.Services.AddDbContext<SchoolDbContext>(options =>
options.UseSqlServer(builder.Configuration["Data:SchoolLocal:ConnectionString"]));
WebApplication app = builder.Build();
// /sf/answers/4988082851/
SchoolDbContext dbcontext = app.Services.GetRequiredService<SchoolDbContext>();
dbcontext.Database.EnsureCreated();
...
Run Code Online (Sandbox Code Playgroud)
帮助会很棒。