Ren*_*ado 6 asp.net-mvc entity-framework-core asp.net-core-mvc
我正在使用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>();
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我可以使用以下命令获取ApplicationDbContext的实例:
[FromServices]
public ApplicationDbContext DbContext { get; set; }
Run Code Online (Sandbox Code Playgroud)
但我无法使用上面的自我段代码在我的Repository实现中获取ApplicationDbContext的实例.
使用MVC 5,我在我的存储库中使用了ServiceLocator并使用了ApplicaionDbContext:
var context = ServiceLocator.Current.GetInstance<ApplicationDbContext>()
Run Code Online (Sandbox Code Playgroud)
如何使用Asp.NET MVC 6在我的存储库中获取ApplicationDbContext的实例?
您可能想要的是使用AddScoped,而不是AddTransient,以便在请求结束时可以正确清理上下文。
您还需要实际添加Context,而不仅仅是AddEntityFramework调用...
services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<ApplicationDbContext, ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2493 次 |
| 最近记录: |