EF Core 2.1 下使用DI注入技巧
最近想学习 EF Core 的用法。根据网上其他人的文章和官方网站上的步骤操作后发现行不通。
我参考的是 https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db
我的 DbContext没有无参构造方法
结果运行后报错:
An unhandled exception occurred while processing the request.
InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
1 // This method gets called by the runtime. Use this method to add services to the container. 2 public void ConfigureServices(IServiceCollection services) 3 { 4 services.Configure<CookiePolicyOptions>(options => 5 { 6 // This lambda determines whether user consent for non-essential cookies is needed for a given request. 7 options.CheckConsentNeeded = context => true; 8 options.MinimumSameSitePolicy = SameSiteMode.None; 9 }); 10 var dbbuilder = new DbContextOptionsBuilder<EcolDbContext>() 11 .UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")); 12 services.AddDbContext<EcolDbContext>(options => options = dbbuilder); 13 services.AddScoped<EcolDbContext>((p) => { return new EcolDbContext(dbbuilder.Options); }); 14 15 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 16 }
services.AddScoped<EcolDbContext>((p) => { return new EcolDbContext(dbbuilder.Options); });
是重点。利用.netcore自带的 依赖注入 功能注入 EcolDbContext。
然后在Controller的构造函数里传入EcolDbContext
希望对大家有用。