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.

I install Unity using the Unity.MVC NuGet package. This creates a UnityConfig.cs file in the App_Start folder. I use the following RegisterType() method for automatic type registration as long as the interface has the same name as the class but begins with the capitol I convention (Car.cs and ICar.cs for example).


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 the Identity Sample 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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s