Making ASP.NET Identity and Unity Work Together

The beauty of ASP.NET MVC is its ability to leverage so many other frameworks to help improve code security, maintainability and SOLID development principles. One downfall however is that these different frameworks don’t always want to work together out of the box at times such as Identity for authentication and authorization and Unity for dependency injection. This is not very difficult to fix as long as you know what you need to add where. 

The root of the problem between these two frameworks is that by default Unity wants to call the constructor of all objects that has the most arguments. By default Identity wants the default or empty constructor called. Because of this once you install Unity you are no longer able to login to your application because it breaks Identity. The fix to this is to register 2 to 4 types depending on your usage of Identity.

In order to fix the basic functionality of Identity we need to register types for the AccountController and the ManageController and instruct Unity to call the empty constructor. This can be done by adding the following RegisterTypes to the RegisterTypes() method as well.

container.RegisterType<AccountController>(new InjectionConstructor());
container.RegisterType<ManageController>(new InjectionConstructor());

This will take care of basic Identity, however if you have installed my NuGet package for User and Role administration you will also need to add the following type registrations.

container.RegisterType<UsersAdminController>(new InjectionConstructor());
container.RegisterType<RolesAdminController>(new InjectionConstructor());

That should do it. You can now rebuild and run your application and the Identity features should work with Unity installed.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *