[英]How can you inject an asp.net mvc3 custom membership provider using Autofac?
I have an MVC3 app using Autofac and a custom membership provider. 我有一个使用Autofac和自定义成员资格提供程序的MVC3应用程序。
If I try and inject the provider using the ctor, I get an error: 'No parameterless constructor defined for this object.' 如果我尝试使用ctor注入提供程序,我会收到一个错误:'没有为此对象定义无参数构造函数。'
public class MyMemberShipProvider : MembershipProvider
{
IUserRepository userRepository;
public MyMemberShipProvider(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
You can not inject into the in-built providers (Membership / Roles). 您无法注入内置提供程序(成员资格/角色)。 You can use the MVC 3 DependencyResolver with Autofac. 您可以将MVC 3 DependencyResolver与Autofac一起使用。
A quick example... 一个简单的例子......
public override bool ValidateUser(string username, string password)
{
var userRepo = DependencyResolver.Current.GetService<IUserRepository>();
return userRepo.ValidateUser(username, password);
}
Avoid resolving in application code (validate user, etc) as this is the service locator anti-pattern. 避免在应用程序代码中解析(验证用户等),因为这是服务定位器反模式。 You want to resolve only in your 'glue' code/low level code. 您只想在“胶水”代码/低级代码中解决。
This below is for windsor, but the implementation can be easily adjusted. 以下是针对windsor的,但可以轻松调整实施方案。 Here is one outlined for castle windsor, but the implementation should be similar. 这是一个针对城堡温莎的概述,但实施应该是类似的。 Its a bit cleaner as this resolves in the call to GetProvider - which is the 'glue' code here, thus avoiding the service locator anti-pattern usage in the actual membership functions (such as ValidateUser) 它有点干净,因为这在GetProvider调用中解决 - 这里是'粘合'代码,因此避免了实际成员函数中的服务定位器反模式使用(例如ValidateUser)
http://bugsquash.blogspot.com/2010/11/windsor-managed-membershipproviders.html http://bugsquash.blogspot.com/2010/11/windsor-managed-membershipproviders.html
That´s because you should inject your userRepository as well. 这是因为你也应该注入你的userRepository。 Something like: 就像是:
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<UserRepository>().As<IUserReposotory>();
builder.RegisterType<MyMembershipProvider>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.