【问题标题】:ASP.NET Core Dependency Injection, inject with parametersASP.NET Core 依赖注入,带参数注入
【发布时间】:2016-07-03 23:21:44
【问题描述】:

在 ASP.NET Core 1.0 项目中,如何使用 DI 将参数传递给构造函数。例如,如何在 Startup.cs 中注册以下服务。 services.AddTransient(typeof(IStateService), new StateService()); 不起作用,因为 StateService() 需要 BlogingContext 类型的输入参数。或者,是否有替代方法来构建涉及数据库的以下服务?这里State 是一个来自 SQL Server Db 的表。应用程序正在使用 EntityFrameworkCore 和 Code First 方法。我正在使用 2016 年 6 月 27 日发布的 ASP.NET Core 1.0 和 VS2015-Update 3 的最新版本

我看到了一个similar example here,但输入参数的类型并不完全相同。

服务

    public interface IStateService
    {
        IEnumerable<State> List();
    }

     public class StateService : IStateService
     {
         private BloggingContext _context;

         public StateService(BloggingContext context)
         {
             _context = context;
         }

         public IEnumerable<State> List()
         {
             return _context.States.ToList();
         }
     }

【问题讨论】:

  • 你有没有试过在启动时用services.AddDbContext&lt;BloggingContext&gt;();之类的东西注册BloggingContextdocs.asp.net/en/latest/fundamentals/…
  • @mollwe 感谢您的帮助。您的代码不会注册我的自定义服务,即StateService
  • 如果您将状态服务注册为service.AddTransient&lt;IStateService, StateService&gt;();,那会成功吗?
  • @mollwe 但是 StateService() 构造函数需要一个 BloggingContext 类型的参数。这就是 VS 所抱怨的。
  • 如果向下滚动一点,就会有一个带有 ICharacterRepository 和 ApplicationDbContext 的 CharacterController。再往下,他们将它们注册为 DI。 ICharacterRepository 匹配您的 IStateService 并且 ApplicationDbContext 匹配您的 BloggingContext...

标签: c# asp.net-core visual-studio-2015 dependency-injection entity-framework-core


【解决方案1】:

正如文档所述 here(向下滚动一点),您应该注册 IStateServiceBloggingContext,例如:

services.AddDbContext<BloggingContext>();
services.AddScoped<IStateService, StateService>();

然后 DI 将为您解析整个依赖关系树。请注意,您应该在服务上使用作用域生命周期,因为服务应该使用与 DbContext 相同的生命周期并且它使用作用域。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    相关资源
    最近更新 更多