20

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

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?

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

Sasuke Uchiha
  • 857
  • 2
  • 11
  • 23

1 Answers1

30

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

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();

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

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);

WARNING: Do not register your controllers as Singleton in case they derive from Controller or ControllerBase, as these classes contain state (as @MarcoPelegrini correctly notes in the comments), while Singletons should be stateless.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • 2
    Beware that if your controller keeps state making it singleton is a problem. E.g. in .NET 3.1 if you inherit from Controller / ControllerBase, my understanding is that ViewData and other fields are state that shouldn't be shared. – Marco Pelegrini Jul 04 '22 at 20:46
  • 1
    @MarcoPelegrini, you are absolutely correct. You should never try this using ASP.NET (classic), as controllers store state. This question (and answer) targets ASP.NET Core, but even then you need to be careful not to store any state in your controller. – Steven Jul 05 '22 at 14:02
  • 1
    Even for .NET Core there is state kept in the controller/controllerbase: https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.ViewFeatures/src/Controller.cs – Marco Pelegrini Jul 06 '22 at 16:30
  • 1
    @MarcoPelegrini: that's a good observation. I will add a warning. – Steven Jul 07 '22 at 08:17