ASP.net Identity, IoC and sharing DbContext

半世苍凉 提交于 2019-12-02 21:25:17

EDIT: added instantiating the OWIN pipeline as per comment.

As the IdentityDbContext used by ASP.NET Identity inherits from DbContext, you can simply create your own implementation inheriting from IdentityDbContext like so

public class ApplicationContext : IdentityDbContext<ApplicationUser>
{
     //additional DbSets
    public DbSet<OtherEntity> OtherEntities { get; set; } 
}

public class ApplicationUser : IdentityUser
{
    //any custom properties you want for your user.
}

public class OtherEntity
{
    [Key]
    public int Id { get; set; }
}

now as far as using IoC, from a unity perspective, I register an instance of the UserStore like so

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new InjectionConstructor(typeof(ApplicationContext)));
}

then create a wrapper around the user manager

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store)
    {
    }
}

and inject that wherever I need a user manager.

As for the OWIN pipeline, you need to instantiate the OAuthAuthorizationProvider through your container, like so.

container.RegisterType<IOAuthAuthorizationServerProvider, ApplicationOAuthProvider>(new InjectionConstructor("self", typeof(ApplicationUserManager)));

then for example in WebApi, you need to simply get the instance from the container in startup.

static Startup()
        {
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = (IOAuthAuthorizationServerProvider)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IOAuthAuthorizationServerProvider)),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(5),
                AllowInsecureHttp = true,
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!