首页 > 解决方案 > IServiceCollection - 依赖注入?在哪里可用?

问题描述

我正在通过复数视频学习 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 内置了它吗?或者这有什么不同?

标签: c#asp.net-coredependency-injection

解决方案


谁在实例化它,它的生命周期是什么,以及它在哪里可用。

框架将使用您在 DI 容器中注册时指定的生命周期来实例化服务。您注册的所有服务都可以在包含您的 DI-Container 的主项目中引用的项目中使用。

这是在做我使用 Autofac 之类的依赖注入框架所做的事情,但是 ASP.NET Core 内置了它吗?或者这有什么不同?

一切都与其他 DI 容器相同,例如AutoFac. DI 是使用名为Microsoft.Extensions.DependencyInjection的 ASP.NET Core 的内置 DI 容器完成的


推荐阅读