ASP.net Identity, IoC and sharing DbContext

后端 未结 1 1854
没有蜡笔的小新
没有蜡笔的小新 2021-02-03 15:15

Have anyone been successful in attaching an IoC with OWIN ASP.NET Identity to share the same DbContext as the WebApi (or MVC) application?

I would like that if ASP.Net i

相关标签:
1条回答
  • 2021-02-03 15:38

    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()
                };
            }
    
    0 讨论(0)
提交回复
热议问题