我必须将Oauth与Autofac集成。但有些事情出错了。我想我明白为什么,但我不知道如何解决它。我让你看看我的代码。通过Autofac 4.0配置OAuthAuthorizationServerProvider
我Autofac配置
{
builder.RegisterType<CustomAuthorizationServerProvider>()
.PropertiesAutowired()
.SingleInstance();
builder.RegisterType<MyBusinessObj>()
.As<IMyBusinessObj>()
.InstancePerRequest()
.PropertiesAutowired();
//IMySessionObj is a prop inside MyBusinessObj
builder.RegisterType<MySessionObj>()
.As<IMySessionObj>()
.InstancePerRequest()
.PropertiesAutowired();
//IMyUnitOfWorkObjis a prop inside MyBusinessObj
builder.RegisterType<MyUnitOfWorkObj>()
.As<IMyUnitOfWorkObj>()
.InstancePerRequest();
...
}
Startup.cs
我有经典配置加上我authorizationServerProvider
..分辨率正如你所看到的,我解决它在容器中。 ..因为它是一个单身人士。
app.UseAutofacMiddleware(_container);
app.UseAutofacWebApi(config);
var oauthServerOptions = new OAuthAuthorizationServerOptions
{
...,
Provider = _container.Resolve<CustomAuthorizationServerProvider>()
};
app.UseOAuthAuthorizationServer(oauthServerOptions);
app.UseWebApi(config);
CustomAuthorizationServerProvider.cs
这是怎么了我已经实现了我的CustomAuthorizationServerProvider
。
public class CustomAuthorizationServerProvider: OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
var myBusinessObj = autofacLifetimeScope.Resolve<IMyBusinessObj>();
var xxx = myBusinessObj.DoWork();
...
return Task.FromResult<object>(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var myBusinessObj = autofacLifetimeScope.Resolve<IMyBusinessObj>();
var xxx = myBusinessObj.DoWork();
...
context.Validated(ticket);
}
}
在这里我解决了我的IMyBusinessObj
在lifetimescope中,而不是在容器中。这个对象负责(间接)连接到数据库,访问会话,访问缓存等......所以它不能是单身。
我需要它会有一个生命周期的每个请求。 所以这里的问题..我的配置有两个问题。
我有一个
SingleInstance
对象内InstancePerRequest
对象。我不能这样做。 Troubleshooting Per-Request Dependencies当我在启动时配置oauth时,我实际上不能有一个
InstancePerRequest
对象...因为在该上下文中不存在请求。
所以..我已经理解了哪些是我的问题。
任何想法或提示? 谢谢