我正在尝试将DI与OWIN CreatePerOwinContext
扩展名一起使用。我也在使用OAuthAuthorizationServerProvider
。在OAuthAuthorizationServerProvider内部,我试图使用以下内容获取我的用户管理器实例:OAuthGrantResourceOwnerCredentialsContext.OwinContext.GetUserManager。
启动UP文件:
public void Configuration(IAppBuilder app)
{
DataProtectionProvider = app.GetDataProtectionProvider();
var config = new HttpConfiguration {DependencyResolver = new UnityDependencyResolver(UnityRegistrations.GetConfiguredContainer())};
WebApiConfig.Register(config);
//Allow Cross Domain Calls
app.UseCors(CorsOptions.AllowAll);
//I verified that my AppUserManager is getting constructed properly
//var manager = UnityRegistrations.GetConfiguredContainer().Resolve<AppUserManager>();
app.CreatePerOwinContext(() => UnityRegistrations.GetConfiguredContainer().Resolve<AppUserManager>());
OAuthOptions = new OAuthAuthorizationServerOptions
{
// Point at which the Bearer token middleware will be mounted
TokenEndpointPath = new PathString("/token"),
// An implementation of the OAuthAuthorizationServerProvider which the middleware
// will use for determining whether a user should be authenticated or not
Provider = new OAuthProvider("self"),
// How long a bearer token should be valid for
AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
// Allows authentication over HTTP instead of forcing HTTPS
AllowInsecureHttp = true
};
app.UseOAuthBearerTokens(OAuthOptions);
app.UseWebApi(config);
}
这是GetConfiguredContainer
方法:
private static readonly Lazy<IUnityContainer> Container = new
public static IUnityContainer GetConfiguredContainer()
{
return Container.Value;
}
Lazy<IUnityContainer>(() => {
var container = new UnityContainer();
//Registers the Types
Register(container);
return container;
});
在GrantResourceOwnerCredentials
实施的OAuthAuthorizationServerProvider
内,我尝试获取AppUserManager
的实例:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//Inspecting the _userManager I see the ObjectDisposedException
_userManager = context.OwinContext.GetUserManager<AppUserManager>();
var user = await _userManager.FindByNameAsync(context.UserName);
}
我正在尝试使用Web API和Owin做什么?
答案 0 :(得分:0)
AppUserManager
Unity注册时添加了HierarchicalLifetimeManager
。这显然是一个错误。它过早地处置了。我的DbContext注册时也有HierarchicalLifetimeManager
。欢乐时光!
<强> WRONG 强>
_unityContainer.RegisterType<AppUserManager>(new HierarchicalLifetimeManager());
<强>正确强>
_unityContainer.RegisterType<AppUserManager>();