I am trying to use DI with the the OWIN CreatePerOwinContext
extension. I am also using the OAuthAuthorizationServerProvider
. Inside the OAuthAuthorizationServerProvider I am trying to get and instance of my user manager using: OAuthGrantResourceOwnerCredentialsContext.OwinContext.GetUserManager.
Start UP file:
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);
}
This is the GetConfiguredContainer
method :
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;
});
Inside the GrantResourceOwnerCredentials
of my OAuthAuthorizationServerProvider
implementation I try to get an instance of the 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);
}
Is what I am trying to do even possible with Web API and Owin?
I made a rookie mistake. For some reason on my AppUserManager
Unity registration I added a HierarchicalLifetimeManager
. This was, obviously, a mistake. It was disposing prematurely. My DbContext also has a HierarchicalLifetimeManager
on its registration. Hours of fun!
WRONG
_unityContainer.RegisterType<AppUserManager>(new HierarchicalLifetimeManager());
Correct
_unityContainer.RegisterType<AppUserManager>();