问题
I'm trying to implement a role provider using a separate EF repository class, as an injectable dependency, to access my roles store. My problem is that the role provider is defined in configuration (web.config) and therefore is not instantiated via the Unity DI container. I haven't been able to find a way to either shift the configuration to code or get hold of the role provider after it's built to call container.BuildUP() on it. Any suggestions would be appreciated.
回答1:
I think that my question's solution is fairly well covered here:
Property injection in custom membership provider using Castle
If I'd searched on MembershipProvider instead of RoleProvider probably would have found it the first time through.
Just to summarize my solution, the link lead me to the Common Service Locator library at codeplex.
It and the Unity adapter for it are included in the Nuget package for Unity 3. So I already had it.
I added one line to the end of the Compose() method of my CompositionRoot class:
var locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
And I can now access the locator/container thru the static ServiceLocator class in the constructor of my RoleProvider:
public IAuthorizationManager Manager {get; set;}
public MyRoleProvider()
{
var locator = ServiceLocator.Current;
Manager = locator.GetInstance<IAuthorizationManager>();
}
(Of course, you need 'using' statements for Microsoft.Practices.ServiceLocation)
来源:https://stackoverflow.com/questions/22331355/unity-dependency-injection-in-an-asp-mvc-5-0-roleprovider-defined-in-configurati