ASP.net, IoC, and DbContext Sharing

Has anyone managed to connect an IoC with an OWIN ASP.NET identifier to share the same DbContext as a WebApi (or MVC) application?

I would like that if the ASP.Net identifier loads the user, it loads in the same dbcontext as the rest of the application.

(using AutoFac as IoC - but don't mind the example with another container)

Edit : 06 / Jan / 2014: To be more specific, when an ASP.Net identifier tries to use a DbContext, it must be the same DbContext instanceas the rest of the application. Otherwise, it will create two instances of the same DbContext. I am already using the extension .PerHttpApiRequest().

The problem that I discovered is that when setting up the OWIN classes, I could not find a way: 1) attach the container to the OWIN pipeline; 2) tell OWIN to allow the classes it needs using this container so that it can use the same scope (e.g. OAUthServerOptions or any other that may contain other dependencies)

Having said that, how can you configure the ASP.Net identifier by resolving the two points above?

+3
source share
1 answer

EDIT: added instantiation of the OWIN pipeline according to the comment.

IdentityDbContext, ASP.NET Identity, DbContext, , IdentityDbContext

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; }
}

, IoC, , UserStore, ,

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

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

, .

OWIN, OAuthAuthorizationProvider , .

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

, , WebApi, .

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()
            };
        }
+3

Source: https://habr.com/ru/post/1545179/


All Articles