我正在使用Asp.Net MVC 6 beta4和Repository Pattern。
在我的Startup.cs中我有這樣的東西:
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
//Dependency Injection
services.AddTransient<IProductRepository, ProductRepository>();
在我的Controller中,我可以使用以下命令獲取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,以便在請求結束時正確清理上下文。
您還需要實際添加Context,而不僅僅是AddEntityFramework調用...
services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<ApplicationDbContext, ApplicationDbContext>();