views:

365

answers:

4

Consider:

public class HomeController : Controller {

    private IDependency iDependency;

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

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?

(*) You end up with the yellow screen of death otherwise.

+1  A: 

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

Rob
+4  A: 

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.

JohannesH
+2  A: 

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;
    }
}
Dale Ragan
+1  A: 

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

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