如何使用 Autofac 注入 ASP.NET MVC3 自定义成员资格提供程序?
我有一个使用 Autofac 的 MVC3 应用程序和一个自定义会员资格提供程序。
如果我尝试使用构造函数注入提供程序,则会收到错误:“没有为此对象定义无参数构造函数。”
public class MyMemberShipProvider : MembershipProvider
{
IUserRepository userRepository;
public MyMemberShipProvider(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
I have an MVC3 app using Autofac and a custom membership provider.
If I try and inject the provider using the ctor, I get an error: 'No parameterless constructor defined for this object.'
public class MyMemberShipProvider : MembershipProvider
{
IUserRepository userRepository;
public MyMemberShipProvider(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法注入内置提供程序(成员资格/角色)。
您可以将 MVC 3 DependencyResolver 与 Autofac 结合使用。
一个简单的例子...
You can not inject into the in-built providers (Membership / Roles).
You can use the MVC 3 DependencyResolver with Autofac.
A quick example...
避免在应用程序代码中解析(验证用户等),因为这是服务定位器反模式。您只想在“粘合”代码/低级代码中进行解析。
下面是针对温莎的,但可以轻松调整实现。这是温莎城堡的概述,但实现应该类似。它更干净一些,因为这在对 GetProvider 的调用中解析 - 这是此处的“粘合”代码,从而避免了实际成员函数(例如 ValidateUser)中的服务定位器反模式使用
http://bugsquash.blogspot.com/2010/11/windsor-management-membershipproviders.html
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. 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)
http://bugsquash.blogspot.com/2010/11/windsor-managed-membershipproviders.html
那是因为你也应该注入你的 userRepository 。像这样的东西:
That´s because you should inject your userRepository as well. Something like: