Custom Owin middleware eventually needs to verify credentials against the database, yet I can't find a way to get instances of repositories or the Asp.Net Identity UserManager
from the middleware via DI.
Unfortunately my database driver is a global singleton and should be resolved by the configured Unity container. When debugging, the Unity child container for the request is created after the middleware gets called.
Is there any way to resolve dependencies with Unity in the middleware?
I tried this without success, but the namespace seems to be wrong anyway (System.Web.Mvc vs System.Web.Http)
var userManager = DependencyResolver.Current.GetService<ApplicationUserManager>();
It seems Autofac solves this by creating the request scope as a middleware itself. What about Unity?
UPDATE
This works
var userManager = (ApplicationUserManager)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(ApplicationUserManager));
However the child container (BeginScope of IDependencyResolver
) is created later. I registered the UserManager with a HierarchicalLifetimeManager
, which probably means it resolves a single instance in the parent container and subsequent requests get the same instance.
What's safer, using a TransientLifetimeManager
and just resolve in the parent container, or are there better options?