ASP.NET Core 依赖注入,带参数注入

3
在ASP.NET Core 1.0项目中,使用DI如何向构造函数传递参数?例如,我该如何在Startup.cs中注册以下服务:services.AddTransient(typeof(IStateService), new StateService());,因为StateService()需要一个BlogingContext类型的输入参数,所以这样做是行不通的。或者,有没有其他涉及数据库的构建以下服务的方法?这里的State是来自SQL Server数据库的表。应用程序使用基于Code First方式的EntityFrameworkCore。我正在使用发布于2016年6月27日的最新版本的ASP.NET Core 1.0和VS2015-Update 3。
我在这里看到了一个类似的例子,但它的输入参数类型不完全相同。 服务:
    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<BloggingContext>(); 这样的方式注册 BloggingContext 吗?详情请见 https://docs.asp.net/en/latest/fundamentals/dependency-injection.html#registering-your-own-services - mollwe
@mollwe 感谢您的帮助。您的代码无法注册我的自定义服务,即 StateService - nam
但是,如果您按照我的两个评论中所述添加了db上下文和服务,则DI应该解决它,我认为,尽管我没有测试过,但这就是其他人的工作方式,例如Autofac。 - mollwe
1
如果你往下滚一点,就会看到一个带有ICharacterRepository和ApplicationDbContext的CharacterController。更进一步地,它们被注册到了DI容器中。其中,ICharacterRepository对应你的IStateService,而ApplicationDbContext则对应你的BloggingContext... - mollwe
@mollwe 没错。你想把你的解决方案写成答案,我会接受它作为答案。谢谢你的帮助。 - nam
显示剩余5条评论
1个回答

2
根据文档所述,您应该像这样注册和:(请参阅此处(向下滚动)链接)。请注意保留HTML标签。
services.AddDbContext<BloggingContext>();
services.AddScoped<IStateService, StateService>();

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接