如何在 Repository MVC6 中注入 ApplicationDbContext 的依赖

How to Inject Dependency of ApplicationDbContext in Repository MVC6

我正在使用 Asp.Net 带有存储库模式的 MVC 6 beta4。

在我的 Startup.cs 我有这样的东西:

services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>(options => 
                        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

//Dependency Injection
services.AddTransient<IProductRepository, ProductRepository>();

在我的控制器中,我可以获得我的 ApplicationDbContext 实例:

[FromServices]
public ApplicationDbContext DbContext { get; set; }

但是我无法在我的 Repository 实现中使用上面的自段代码获取 ApplicationDbContext 的实例。

对于 MVC 5,我在我的存储库中使用了 ServiceLocator 并采用了 ApplicaionDbContext,因此:

var context = ServiceLocator.Current.GetInstance<ApplicationDbContext>()

如何使用 Asp.NET MVC 6 在我的存储库中获取 ApplicationDbContext 实例?

您可能想要使用 AddScoped,而不是 AddTransient,以便在请求结束时正确清理上下文。

您还需要实际添加上下文,而不仅仅是 AddEntityFramework 调用...

services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<ApplicationDbContext, ApplicationDbContext>();