团结依赖注入的自定义成员资格提供 [英] Unity dependency injection in custom membership provider
问题描述
我有,我想使用自定义的成员提供ASP.NET MVC3项目。此外,我想用团结来解决我的依赖注入。
I have ASP.NET MVC3 project where I want to use custom membership provider. Also I want to use Unity for resolving my dependency injection.
这是从Global.asax中code:
this is code from Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var container = new UnityContainer();
container.RegisterType<IAuthentification, Authentification>();
container.RegisterType<IRepository, Repository>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
这是code从我的会员供应商:
this is code from my membership provider:
public class CustomMembershipProvider : MembershipProvider
{
[Dependency]
private IProveaRepository Repository { get; set; }
public override bool ValidateUser(string username, string password)
{
.....
}
问题是,当我把断点ValidateUser方法我看到库属性未初始化。但是,这种结构:
Problem is when I put breakpoint to ValidateUser method I see that Repository property not initialized. But this construction:
[Dependency]
private IProveaRepository Repository { get; set; }
例如,在控制器正常工作。
for example, works fine in controllers.
是否有人知道为什么会这样,以及怎样做?
Does anybody know why it is so and what to do?
推荐答案
我有同样的问题在过去的几天。我结束了以下解决方案(类型,字段名更改以匹配你的)。
I had the same problem over the last couple of days. I ended up with the following solution (type and field names changed to match yours).
public class CustomMembershipProvider : MembershipProvider
{
private IProveaRepository repository;
public CustomMembershipProvider()
: this (DependencyResolver.Current.GetService<IProveaRepository>())
{ }
public CustomMembershipProvider(IProveaRepository repository)
{
this.repository= repository;
}
public override bool ValidateUser(string username, string password)
{
...
}
}
所以,即使团结是不是在建设控制在 CustomMembershipProvider
,无参数的构造函数将被统一involed(通过MVC3 DependencyResolver
),以提供正确的存储库实例。
So even though Unity is not in control of the building of the CustomMembershipProvider
, the parameterless constructor gets Unity involed (via the MVC3 DependencyResolver
) to supply the correct repository instance.
如果你是单元测试 CustomMembershipProvider
那么你可以建立与统一直接的实例,将使用第二个构造,避免调用 DependencyResolver
。
If you're unit testing the CustomMembershipProvider
then you can just build an instance with Unity directly, which will use the second constructor and avoid the call to DependencyResolver
.
这篇关于团结依赖注入的自定义成员资格提供的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!