与Ninject的自我绑定成员资格提供者

时间:2010-10-14 16:00:08

标签: asp.net-mvc ninject

我试图在ASP.NET MVC 2中自我绑定MembershipProvider,然后在AccountController构造函数中使用此绑定。

这是我的global.asax.cs

的片段
// selfbind MembershipProvider in request scope
Bind<MembershipProvider>().ToSelf().InRequestScope();

服务类的片段:

public AccountMembershipService(MembershipProvider provider, IAccountRepository accountRepository)
{
    _provider = provider ?? Membership.Provider;
    _accountRepository = accountRepository;
}

我的问题是注入不起作用(但是AccountRepository的注入确实有效)。这是Ninject的错误:

Error activating MembershipProvider using self-binding of MembershipProvider
No constructor was available to create an instance of the implementation type.
Activation path:
   3. Injection of dependency MembershipProvider into parameter provider of constructor of type AccountMembershipService
   2. Injection of dependency IMembershipService into parameter membershipService of constructor of type AccountController
   1. Request for IController

Suggestions:
 1) Ensure that the implementation type has a public constructor.
 2) If you have implemented the Singleton pattern, use a binding with InSingletonScope() instead.

设置InSingletonScope()没有任何区别,我无法对构造函数做任何事情,因为这不是自定义MembershipProvider,而是ASP.NET附带的默认值。

我被困在这里,不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:4)

好的,找到了。我错误地将MembershipProvider设置为self,这无法工作,因为MembershipProvider是抽象类。

这有效

Bind<MembershipProvider>().ToConstant(Membership.Provider);

答案 1 :(得分:2)

您需要在成员资格提供程序上创建一个空的ctor,并在其上创建一个存储库。假设您已正确注册了内核的成员资格提供程序......

    Bind<MembershipProvider>().To<YourMembershipProvider>();
    Bind<IMembershipService>().To<AccountMembershipService>();