【问题标题】:How to Inject Dependency of ApplicationDbContext in Repository MVC6如何在 Repository MVC6 中注入 ApplicationDbContext 的依赖关系
【发布时间】:2015-09-28 05:41:18
【问题描述】:

我正在使用带有存储库模式的 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 实现中使用上面的这个 self 段代码获取 ApplicationDbContext 的实例。

在 MVC 5 中,我在我的存储库中使用了 ServiceLocator 并使用了 ApplicaionDbContext,所以:

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

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

【问题讨论】:

  • 你检查过这个吗? stackoverflow.com/questions/29332494/…
  • 我会到的!谢谢!
  • 为什么要使用属性注入而不是构造函数注入?
  • @ErikFunkenbusch,通过构造注入,我可以像在 MVC6 中使用属性注入一样获得实例吗?因为使用 [FromServices] 我在会话中获得了 ApplicationDbContext。
  • @ErikFunkenbusch 我这样做了吗?

标签: asp.net-mvc asp.net-core-mvc entity-framework-core


【解决方案1】:

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

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

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

【讨论】:

  • 那么,在我的注入库中将由构造函数创建?
  • @RenattoMachado - 我不明白你的意思.. 如果你问是否应该使用构造函数注入,那么是的,你应该.. 除非没有其他方法,然后属性注入将是您将使用的......但仅将属性注入用作最后的手段。
  • 我按照你说的做了,但是我得到了这个错误:No data stores are configured. Configure a data store by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.
  • @RenattoMachado - 你仍然需要 AddEntityFramework(...) 的东西。
  • 会是这个吗? services.AddEntityFramework() .AddSqlServer() .AddDbContext&lt;ApplicationDbContext&gt;(options =&gt; options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));我没有删除这段代码。
猜你喜欢
  • 2018-06-08
  • 1970-01-01
  • 2015-06-04
  • 2015-07-22
  • 1970-01-01
  • 2011-12-31
  • 2018-06-19
  • 2021-11-19
  • 2010-11-24
相关资源
最近更新 更多