Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NET Core: Are MVC Controllers default Singleton?

Tags:

c#

.net

.net-core

I would like to know if the Controller classes of .NET MVC Core are default Singleton?

If not, then do the Framework creates multiple objects of Controller class for each and every request? Isn't it an overhead and costlier to create a new instance of such classes?

In other programming languages like Java, there is only one Instance of Controller class created (Servlet) and each and every request is handled with a new Thread. Doesn't it similar in .Net?

like image 294
NGR Avatar asked Mar 06 '26 00:03

NGR


1 Answers

They're actually declared as Transient:

public static IMvcBuilder AddControllersAsServices(this IMvcBuilder builder)
{
    if (builder == null)
    {
        throw new ArgumentNullException(nameof(builder));
    }

    var feature = new ControllerFeature();
    builder.PartManager.PopulateFeature(feature);

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

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

    return builder;
}

Taken from: https://github.com/aspnet/AspNetCore/blob/c7cb8467bfce721e2d66ef3862cd8c7c1fdbb421/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreMvcBuilderExtensions.cs

Line (150)

like image 63
Robert Perry Avatar answered Mar 07 '26 13:03

Robert Perry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!