I must integrate Oauth with Autofac. But something goes wrong. I think I understand why, but I don't know how to solve it. I let you see my code.
My Autofac Config
{
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
I have the classic configuration plus the resolution of my authorizationServerProvider.. As you can see, I resolve it in the container... because it is a singleton.
app.UseAutofacMiddleware(_container);
app.UseAutofacWebApi(config);
var oauthServerOptions = new OAuthAuthorizationServerOptions
{
...,
Provider = _container.Resolve<CustomAuthorizationServerProvider>()
};
app.UseOAuthAuthorizationServer(oauthServerOptions);
app.UseWebApi(config);
CustomAuthorizationServerProvider.cs
This is how I have implemented my 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);
}
}
Here I solve my IMyBusinessObj in a lifetimescope, not in the container. This object is responsible (indirectly) to connect to db, access the session, access the cache and so on... so it cannot be a singleton.
I need it would have a lifetime per request. So here the problems.. Two problems there are in my configuration.
I have a
InstancePerRequestobject inside aSingleInstanceobject. I cannot do that. Troubleshooting Per-Request DependenciesI effectively cannot have a
InstancePerRequestobject when I configure oauth in the startup... because in that context does not exist a request yet.
So.. I have understood which are my problems.
Any idea or tips? Thank you