【问题标题】:IServiceCollection - Dependency Injection? Available Where?IServiceCollection - 依赖注入?在哪里可用?
【发布时间】:2020-08-17 21:06:31
【问题描述】:

我正在通过复数站点视频学习 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-core dependency-injection


    【解决方案1】:

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

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

    这是在做我使用依赖注入所做的吗 Autofac 之类的框架,但是 ASP.NET Core 是否内置了它?或者这是 不一样?

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

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多