Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container?
I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.
ASP.NET Core MVC controllers request dependencies explicitly via constructors.
A constructor is a special type of method of a C# class which invokes automatically when a new instance of a class is created. Constructor is used in object initialization and memory allocation of the class. Constructor is used to initialize private fields and their values of the class. A constructor can be overloaded.
How can we inject the service dependency into the controller C# Asp.net Core? ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container. The built-in container is represented by IServiceProvider implementation that supports constructor injection by default.
One way is to create a ControllerFactory:
public class MyControllerFactory : DefaultControllerFactory
{
public override IController CreateController(
RequestContext requestContext, string controllerName)
{
return [construct your controller here] ;
}
}
Then, in Global.asax.cs:
private void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(
new MyNamespace.MyControllerFactory());
}
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