如何在 ASP.NET Core 中使控制器作用域或单例而不是瞬态? [英] How to make controllers scoped or singleton instead of transient in ASP.NET Core?

查看:16
本文介绍了如何在 ASP.NET Core 中使控制器作用域或单例而不是瞬态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 ASP.NET Core 中使控制器作用域或单例而不是瞬态?

How to make controllers scoped or singleton instead of transient in ASP.NET Core?

我现在默认情况下控制器注册到具有瞬态生命周期的默认 DI 容器.

I now that by default the controllers are registered with the default DI container with the transient lifetime.

如果我想用不同的生命周期注册它们,我该怎么做?

In case I would like to register them with a different lifetime, how could I do that?

我想知道这仅仅是为了教育目的,以便更好地了解 DI 容器的控制器类型管理.

I want to know that solely for the educational purposes, to better wrap my head around the controller types management by the DI container.

推荐答案

我现在默认情况下控制器注册到具有瞬态生命周期的默认 DI 容器.

I now that by default the controllers are registered with the default DI container with the transient lifetime.

默认情况下,控制器没有注册.默认的 IControllerActivator 无需显式注册即可创建该类型.

By default, controllers are not registered at all. It is the default IControllerActivator that is creating that type without an explicit registration.

如果你想改变这个,你应该调用:

If you want to change this, you should call:

services.AddMvc().AddControllersAsServices();

这将确保控制器已注册,并且原始 IControllerActivator 被替换为一个 (ServiceBasedControllerActivator),该控制器从 DI 容器解析控制器.

This will ensure that controllers are registered and the original IControllerActivator is replaced with one (ServiceBasedControllerActivator) that resolves controllers from the DI container.

AddControllersAsServices 总是使用 Transient 生活方式注册控制器,并且无法覆盖该行为.所以你必须重新实现 AddControllersAsServices:

AddControllersAsServices, unfortunately, always registers the controllers using the Transient lifestyle and there's no way to override that behavior. So you have to re-implement AddControllersAsServices:

public static IMvcBuilder AddControllersAsServices(
    this IMvcBuilder builder, ServiceLifetime lifetime)
{
    var feature = new ControllerFeature();
    builder.PartManager.PopulateFeature(feature);

    foreach (var controller in feature.Controllers.Select(c => c.AsType()))
    {
        builder.Services.Add(
            ServiceDescriptor.Describe(controller, controller, lifetime));
    }

    builder.Services.Replace(ServiceDescriptor
        .Transient<IControllerActivator, ServiceBasedControllerActivator>());

    return builder;
}

这种新的扩展方法可以如下使用:

This new extension method can be used as follows:

services.AddMvc().AddControllersAsServices(ServiceLifetime.Singleton);

这篇关于如何在 ASP.NET Core 中使控制器作用域或单例而不是瞬态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆