14

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?

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

1

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

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.