Can mvc 5 application has IoC out of the box?

926 views Asked by At

How is it possible that fresh mvc 5 application just reated from template has dependencies injected into controller?

public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

This what you can see in Account Controller in just created project.

2

There are 2 answers

3
smartcaveman On BEST ANSWER

ASP.NET MVC 5 exposes multiple injection points that enable the functionality you described.

The most explicit one is the DependencyResolver. The default dependency resolver just does Activator.CreateInstance(controllerType), so it will throw an error if no public parameterless constructor is selected and will not look for greedy constructors.

However, it's fairly simple to enhance this behavior for your use case.

In your global config, add:

DependencyResolver.SetResolver(
   type => { 
       if(type == typeof(AccountController))
       {
           var userManager   = /* resolve the ApplicationUserManager...*/
           var signInManager = /* resolve the ApplicationSignInManager...*/
           return new AccountController(userManager, signInManager);
       }
       else
       { 
          return Activator.CreateInstance(type)
       }
   },
   type => Enumerable.Empty<object>()
);

This solution passes in delegates rather than an IDependencyResolver implementation, but you could just as easily provide a strongly typed resolver instead.

You probably won't get any real value out of doing your IoC configuration this way, but it should be noted that it is completely possible given the ASP.NET MVC 5 framework. The best practice would be to reference the NuGet package for integrating MVC 5 with your preferred container library and let that do the heavy lifting instead. I personally like StructureMap (check out an example of how to do it this way in the selected answer to this post)

2
dgavian On

No. I believe the next version will come with an IOC container, but MVC5 does not