Moving ASP.NET Identity model to class library

I am trying to move the Identity model to a class library using the methods in this link:

ASP.NET Identity in Services library

Problem 1: It seems to keep using the Website project's connection string. I overcame it by specifying the full connection string in the class library. Can I make the IdentityDbContext use the class library's connection string?

Problem 2: Due to the problem 1, if I remove the Entity Framework from the website project. It will give the following error that it is looking for EF's SqlClient in the Website project.

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

Other solutions are welcome as long as it omits all Data Access Layer references like EF in the Website project.


To move the IdentityModel into a class library (which is the right thing to do according to the SRP), follow these steps:

  1. Create a class library. (ClassLibrary1)
  2. Using NuGet, add a reference to Microsoft.AspNet.Identity.EntityFramework. This will also auto-add some other references.
  3. Add a reference in your website to ClassLibrary1
  4. Find WebSite/Models/IdentityModel.cs and move it to ClassLibrary1.
  5. Make IdentityModel.cs look like this:

    public class ApplicationUser : IdentityUser
    {
    }
    
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("YourContextName")
        {
        }
    }
    
  6. Make sure your website's Web.config has YourContextName pointing to the right database in the section. (Note: this database can and should house your application data).

    <add name="YourContextName" connectionString="YourConnectionStringGoesHere"
      providerName="System.Data.SqlClient" />
    
  7. Make your EF Context class inherit from your ApplicationDbContext:

    public class YourContextName : ApplicationDbContext
    {
        public DbSet<ABizClass1> BizClass1 { get; set; }
        public DbSet<ABizClass2> BizClass2 { get; set; }
        // And so forth ...
    }
    

When anyone in your site tries to log in or register, the Identity system will route them to your database with all your data which includes the Identity tables.

Good to go!


An update to @Rap's answer for EF6 and Identity 2.0:

  1. Create a class library. (ClassLibrary1)
  2. Using NuGet, add a reference to Microsoft.AspNet.Identity.EntityFramework and Microsoft.AspNet.Identity.Owin.
  3. Add a reference in your website to ClassLibrary1
  4. Find WebSite/Models/IdentityModel.cs and move it to ClassLibrary1.
  5. IdentityModel.cs should look like this, no need to change anything:

    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
            // Add custom user claims here
            return userIdentity;
        }
    }
    
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }
    
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
    
  6. Make sure your website's Web.config has a context pointing to the right database in the section. (Note: this database can and should house your application data).

    <connectionStrings>
      <add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=Project;Integrated Security=sspi;Pooling=false;" providerName="System.Data.SqlClient" />
    </connectionStrings>
    
  7. Make your EF Context class inherit from your ApplicationDbContext:

    public class YourContextName : ApplicationDbContext
    {
        public DbSet<ABizClass1> BizClass1 { get; set; }
        public DbSet<ABizClass2> BizClass2 { get; set; }
        // And so forth ...
    }
    

What do you mean by moving Identity into a class library? to be used as a reference? I have my custom user manager and user in a separate library, but thats all.

The identity stuff requires a data store of some sort. If you configure Identity to use EF, be sure to get the additional nuget package for it, and you should be able to pass the connection string when you create the context.

Off the top of my head...

var mgr = new UserManager<ApplicationUser>(
     new IUserStore_ofYourChoice<ApplicationUser>(
       new DbContextName("ConnectionStringOverload"));

I think the EF store is "UserStore", gotta verify.

There are nearly a dozen different nuget packages for datastores for Identity now. You don't have to use EF, but it requires a store of some sort.

** EDIT **

Also, as a reference it will always use the config, and hence its defined connection strings, of the main project by default, thats how its suppose to work, so thats ok.


There are a few rules you must be cognizant of and remember.

First, the Web project will ALWAYS and ONLY use the web.config file(s) that it finds in its own project - period. It does not matter what you put in any other config file anywhere else in your solution. The web project can ONLY use what it finds in its own project. If you have a connection string in another project, you must replicate it to the web project, else it will never be found.

Second, assuming the web project is your startup project, and assuming you are using data migrations (since Identity uses it), note that the package manager will AlWAYS use the connection string that it finds in the startup project. Hence, the package manager, for update-database, will not use the connection string in your model project.

The simple solution is: 1. Copy your connection string from your model project to your web project. 2. In the package manager console, make sure that the dropdown to select the context is pointing to your model project.


I suppose i'm a bit late to the party but for the future readers, here's a good read.