gpt4 book ai didi

asp.net - 带有 ASP.Identity 的 AutoFac

转载 作者:行者123 更新时间:2023-12-01 01:00:01 25 4
gpt4 key购买 nike

我将 AutoFac 3.5 与 WebApi 集成 3.3 和 Asp.Identity 2.0.1 一起使用。问题是当我指定时,Asp.Net Identity 有问题 MyDbContext 作为 InstancePerRequest。然后我收到了这种错误消息:

从请求实例的范围中看不到具有匹配“AutofacWebRequest”的标签的范围。这通常表明 SingleInstance() 组件(或类似场景)正在请求注册为每个 HTTP 请求的组件。在 Web 集成下,始终从 DependencyResolver.Current 或 ILifetimeScopeProvider.RequestLifetime 请求依赖项,而不是从容器本身请求依赖项.

我正在像这样注册 Asp Token 提供程序:

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

AutoFac 部分如下所示:
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 Identity, IoC and sharing DbContext

编辑

还有这篇博客文章,有一个凌乱的解决方法 http://blogs.msdn.com/b/webdev/archive/2014/02/12/per-request-lifetime-management-for-usermanager-class-in-asp-net-identity.aspx

最佳答案

我能够通过从 OwinContext 内部获取 AutofacWebRequest 并解析 UserManager 来解决问题。

IOwinContext 被传递给每个 OwinMiddleware 的 Invoke 方法。在里面你可以找到 Enviroment 属性,它是一个 IDictionary,包含很多信息,包括“autofac:OwinLifetimeScope”。
你可以得到这个 LifetimeScope,它应该用标签“AutofacWebRequest”指定,因为它是为每个 http 请求创建的嵌套 Scope,并解析你需要的对象类型。

我的实现看起来与此类似。注意我在UserManagerFactory里面生成UserManager类的方式。

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

}
}

我希望这会有所帮助。如果错过了什么让我知道。

关于asp.net - 带有 ASP.Identity 的 AutoFac,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24300299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com