Finglas
Finglas

Reputation: 15707

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?

Upvotes: 14

Views: 8727

Answers (4)

Dariusz Tarczynski
Dariusz Tarczynski

Reputation: 16731

You can inject your dependency by Property for example see: Injection by Property Using Ninject looks like this:

[Inject]
public IDependency YourDependency { get; set; }

Upvotes: 1

Dale Ragan
Dale Ragan

Reputation: 18270

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;
    }
}

Upvotes: 7

JohannesH
JohannesH

Reputation: 6450

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.

Upvotes: 8

Rob
Rob

Reputation: 1328

Take a look at MVCContrib http://mvccontrib.github.com/MvcContrib/. They have controller factories for a number of DI containers. Windsor, Structure map etc.

Upvotes: 1

Related Questions