ASP.NET Identity Unity and Database first development

Asp Net Identity does a huge amount of work for you when it comes to authentication and third party authentication providers for your site.

Recently I had to implement this with MVC, Entity Framework and Unity for Inversion of Control. I found that out of the box all these elements do not instantly work together within a Database first development.

After a bit of digging I found there were a few small changes that were required to get everything up and running.

Setup Web.Config to have an additional non Entity Framework connection string:

<connectionStrings>
<add name="IdentityConnection" connectionString="Data Source=(local);initial catalog=[DATABASE];User ID=[USERID];Password=[PASSWORD];" providerName="System.Data.SqlClient" />

Ensure you either run it using Integrated security locally the first time to create the table structure or use a user with sufficient permissions to create the Identity table structure.

Modify the connection string reference in IdentityModels.cs to point to your non EF one:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("IdentityConnection", throwIfV1Schema: false) { }    
public static ApplicationDbContext Create() 
{
        return new ApplicationDbContext();
    } }

Finally add the required dependencies to the UnityConfig.cs:

container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<MyAccountController>(new InjectionConstructor());
container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));

Once you run the site for the first time it will setup the relevant tables in your database and you are good to go. This is the quickest way I have found to get everything working almost out of the box.

For reference I tested this with Unity.Mvc 4.0.1, EntityFramework 6.1.3, MVC 5.2.3 and Microsoft.AspNet.Identity 2.2.1.