简体   繁体   English

ASP.NET核心依赖注入,注入参数

[英]ASP.NET Core Dependency Injection, inject with parameters

In an ASP.NET Core 1.0 project, using DI how can I pass parameters to constructor. 在ASP.NET Core 1.0项目中,使用DI如何将参数传递给构造函数。 For instance, how do I register the following service in Startup.cs. 例如,如何在Startup.cs中注册以下服务。 services.AddTransient(typeof(IStateService), new StateService()); does not work since StateService() requires an input parameter of type BlogingContext. 因为StateService()需要一个类型为BlogingContext的输入参数,所以不起作用。 Or, are there alternative way of building the following service with database involved? 或者,是否存在使用数据库构建以下服务的替代方法? Here State is a table coming from SQL Server Db. 这里State是一个来自SQL Server Db的表。 App is using EntityFrameworkCore with Code First approach. 应用程序使用EntityFrameworkCore与Code First方法。 I'm using latest release of ASP.NET Core 1.0 and VS2015-Update 3 released on June 27, 2016 我正在使用2016年6月27日发布的最新版本的ASP.NET Core 1.0和VS2015-Update 3

I see a similar example here but not quite the same type of input parameter. 在这里看到了一个类似的例子,但输入参数的类型并不完全相同。

Service : 服务

    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();
         }
     }

As documentation states here (Scroll a bit down) you should register the IStateService and BloggingContext like: 正如文件指出这里 (滚动了一下下),你应该注册IStateServiceBloggingContext这样的:

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

Then DI will resolve the whole dependency tree for you. 然后DI将为您解析整个依赖关系树。 Note that you should use scoped lifetime on service, because the service should use same lifetime as DbContext and it uses scoped. 请注意,您应该在服务上使用作用域生存期,因为该服务应使用与DbContext相同的生命周期,并且它使用作用域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM