AutoFac with ASP.Identity

I am using AutoFac 3.5 with integration of WebApi 3.3 and Asp.Identity 2.0.1. The problem is that Identity Asp.Net has a problem when im specyfing MyDbContext as InstancePerRequest. Then I got this error:

No area with a tag matching "AutofacWebRequest" is visible from the area in which the instance was requested. This usually indicates that the component registered as an HTTP request is requested by the SingleInstance () component (or a similar script). As part of web integration, dependencies on DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime are always requested, never from the container itself,

I am registering an Asp token provider as follows:

public partial class Startup
{
    static Startup()
    {
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/token"),
            RefreshTokenProvider = (IAuthenticationTokenProvider)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IAuthenticationTokenProvider)),
            Provider = (IOAuthAuthorizationServerProvider)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IOAuthAuthorizationServerProvider)),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
            AllowInsecureHttp = true
        };
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseOAuthBearerTokens(OAuthOptions);
    }
}

And the AutoFac part looks like this:

builder.RegisterType<MyDbContext>().As<DbContext>().InstancePerRequest();
builder.RegisterType<SimpleRefreshToken>().As<IAuthenticationTokenProvider>();
builder.Register(x => new ApplicationOAuthProvider(
                        "self",
                        x.Resolve<Func<UserManager<User>>>()).As<IOAuthAuthorizationServerProvider>();

- ? ASP.net, IoC DbContext

http://blogs.msdn.com/b/webdev/archive/2014/02/12/per-request-lifetime-management-for-usermanager-class-in-asp-net-identity.aspx

+4
1

, AutofacWebRequest OwinContext UserManager.

IOwinContext Invoke OwinMiddleware. Enviroment, IDictionary, , "autofac: OwinLifetimeScope". LifetimeScope, "AutofacWebRequest", , HTTP-, , .

. UserManager UserManagerFactory.

public class Startup
{
    static Startup()
    {
        PublicClientId = "self";

        UserManagerFactory = () =>
        {
            //get current Http request Context
            var owinContext = HttpContext.Current.Request.GetOwinContext();

            //get OwinLifetimeScope, in this case will be "AutofacWebRequest"
            var requestScope = owinContext.Environment.ContainsKey("autofac:OwinLifetimeScope");

            if (!owinContext.Environment.Any(a => a.Key == "autofac:OwinLifetimeScope" && a.Value != null))
                throw new Exception("RequestScope cannot be null...");

            Autofac.Core.Lifetime.LifetimeScope scope = owinContext.Environment.FirstOrDefault(f => f.Key == "autofac:OwinLifetimeScope").Value as Autofac.Core.Lifetime.LifetimeScope;

            return scope.GetService(typeof(UserManager<Models.UserModel>)) as UserManager<Models.UserModel>;

        };

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProviderCustom(PublicClientId, UserManagerFactory),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };
    }

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static Func<UserManager<Models.UserModel>> UserManagerFactory { get; set; }

    public static string PublicClientId { get; private set; }

    public void Configuration(IAppBuilder app)
    {

        var builder = new ContainerBuilder();

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        builder.RegisterType<UserModelsConvert>().InstancePerApiRequest();
        builder.RegisterType<UserStoreCustom>().As<IUserStore<Models.UserModel>>().InstancePerApiRequest();
        builder.RegisterType<UserManager<Models.UserModel>>().InstancePerApiRequest();

        //loading other projects
        builder.RegisterModule(new LogicModule());

        var container = builder.Build();

        app.UseAutofacMiddleware(container);

        //// Create the depenedency resolver.
        var resolver = new AutofacWebApiDependencyResolver(container);

        // Configure Web API with the dependency resolver
        GlobalConfiguration.Configuration.DependencyResolver = resolver;

        app.UseOAuthBearerTokens(OAuthOptions);

        //extend lifetime scope to Web API
        app.UseAutofacWebApi(GlobalConfiguration.Configuration);

        //app.UseWebApi(config);

    }
}

, . -, .

+4

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


All Articles