Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor Dependency Injection in a ASP.NET MVC Controller

Consider:

public class HomeController : Controller 
{
    private IDependency dependency;

    public HomeController(IDependency dependency) 
    {
        this.dependency = dependency;
    }
}

And the fact that Controllers in ASP.NET MVC must have one empty default constructor is there any way other than defining an empty (and useless in my opinion) constructor for DI?

like image 206
Finglas Avatar asked Aug 27 '09 00:08

Finglas


2 Answers

If you want to have parameterless constructors you have to define a custom controller factory. Phil Haack has a great blog post about the subject.

If you don't want to roll your own controller factory you can get them pre-made in the ASP.NET MVC Contrib project at codeplex/github.

like image 171
JohannesH Avatar answered Oct 22 '22 06:10

JohannesH


You don't have to have the empty constructor if you setup a custom ControllerFactory to use a dependency injection framework like Ninject, AutoFac, Castle Windsor, and etc. Most of these have code for a CustomControllerFactory to use their container that you can reuse.

The problem is, the default controller factory doesn't know how to pass the dependency in. If you don't want to use a framework mentioned above, you can do what is called poor man's dependency injection:

public class HomeController : Controller
{

    private IDependency iDependency;

    public HomeController() : this(new Dependency())
    {
    }

    public HomeController(IDependency iDependency)
    {
        this.iDependency = iDependency;
    }
}
like image 27
Dale Ragan Avatar answered Oct 22 '22 08:10

Dale Ragan