IServiceCollection-依赖注入?在哪里可用?

时间:2019-02-15 21:40:33

标签: asp.net-core dependency-injection

我正在通过多个站点的视频学习ASP.NET核心。视频中的同伴告诉我,可以通过在Startup.ConfigureServices中注册,将“服务”添加为单例或瞬态。

public class Startup {

    public Startup() {
    }

    public IConfiguration Configuration { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services) {

        // Register the Greeter as an IGreeter and have the ASP.NET framework register it to be available to anyone who wants an IGreeter
        // Dependency injection?
        services.AddSingleton<IGreeter, Greeter>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IGreeter greeter) {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context) => {
            var greeting = greeter.GetGreeting();
            await context.Response.WriteAsync(greeting);
        });
    }
}

他不清楚是谁在实例化它,它的寿命是什么,以及它在哪里可用。有人可以帮我填写这些详细信息吗?

这是否可以像使用依赖注入框架(如Autofac)那样完成,但是内置了ASP.NET Core?还是不同?

1 个答案:

答案 0 :(得分:1)

  

谁在实例化它,它的生存期是什么,它在哪里   可用。

框架将使用在DI容器中注册服务时指定的生存期来实例化服务。从包含DI容器的主项目引用的项目中,所有注册服务都可用。

  

这是我所做的依赖项注入所要做的吗   框架(例如Autofac),但内置了ASP.NET Core?还是这个   不一样?

一切与其他DI容器(如AutoFac)相同。 DI是使用ASP.NET Core内置的称为 Microsoft.Extensions.DependencyInjection

的DI容器完成的
相关问题