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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With