Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor parameters for controllers without a DI container for ASP.NET MVC

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.

like image 987
Korbin Avatar asked Sep 23 '08 16:09

Korbin


People also ask

Can we use constructor in MVC controller?

ASP.NET Core MVC controllers request dependencies explicitly via constructors.

What is constructor in ASP.NET MVC?

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 in ASP.NET Core?

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.


1 Answers

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());
    }
like image 161
Craig Stuntz Avatar answered Oct 26 '22 11:10

Craig Stuntz