简体   繁体   English

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

[英]IServiceCollection - Dependency Injection? Available Where?

I am learning ASP.NET core though a pluralsite video.我正在通过多站点视频学习 ASP.NET 核心。 The fellow in the video tells me I can add a "service" as a singleton or as a transient, by registering it in Startup.ConfigureServices.视频中的那个人告诉我,通过在 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);
        });
    }
}

He wasn't very clear about who is instantiating it, what its life time is, and where it is available.他不是很清楚谁在实例化它,它的生命周期是多少,以及它在哪里可用。 Can someone fill in those details for me?有人可以帮我填写这些详细信息吗?

Is this doing what I would have done with a dependency injection framework like Autofac, but ASP.NET Core has it built in?这是我在使用 Autofac 这样的依赖注入框架时所做的,但 ASP.NET Core 内置了它吗? Or is this different?或者这是不同的?

who is instantiating it, what its lifetime is, and where it is available.谁在实例化它,它的生命周期是什么,它在哪里可用。

The framework will instantiate the service with the lifetime you specified during registering it in your DI-Container.该框架将使用您在 DI-Container 中注册时指定的生命周期实例化该服务。 All your registered services are available in the projects that have referenced from the main project which contains your DI-Container.您注册的所有服务都可以在从包含您的 DI-Container 的主项目中引用的项目中使用。

Is this doing what I would have done with a dependency injection framework like Autofac, but ASP.NET Core has it built in?这是我在使用 Autofac 这样的依赖注入框架时所做的,但 ASP.NET Core 内置了它吗? Or is this different?或者这是不同的?

Everything is the same as other DI Containers like AutoFac .一切都与AutoFac等其他 DI 容器相同。 DI is done using ASP.NET Core's built-in DI Container called Microsoft.Extensions.DependencyInjection DI 是使用 ASP.NET Core 的内置 DI 容器完成的,称为Microsoft.Extensions.DependencyInjection

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

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