ASP.NET MVC 3 Ninject Custom Membership and Role P

2019-02-13 07:12发布

问题:

Hi i got some problems enabling custom Membership and Role Provider, i got following error:

An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

System.InvalidOperationException: Default Membership Provider could not be found.

It's pointing to my mvc3.ninject kernel.Inject(Membership.Provider)

My MVC3.Ninject in app_start:

private static void RegisterServices(IKernel kernel)
{
    kernel.Inject(Membership.Provider);
    kernel.Inject(Roles.Provider);
    kernel.Bind<IUnitOfWork>().To<EFContext>().InRequestScope();
    kernel.Bind<IUzytkownicyRepository>().To<UzytkownicyRepository>().InRequestScope();            
}  

My RoleProvider:

public class DziennikRoleProvider : RoleProvider
{
    [Inject]
    private IUzytkownicyRepository repository { get; set;}

My MembershipProvider:

public class DziennikMembershipProvider : MembershipProvider
{
    [Inject]
    private IUzytkownicyRepository repository { get; set; }

My WebConfig file:

 <membership defaultProvider="DziennikMembershipProvider">
  <providers>
    <clear/>
    <add name="DziennikMembershipProvider" type="Dziennik_MVC.Helpers.DziennikMembershipProvider, Dziennik_MVC" connectionStringName="EFDbContext"
         applicationName="/" />
  </providers>
</membership>

<profile>
  <providers>
    <clear/>
  </providers>
</profile>

<roleManager defaultProvider="DziennikRoleProvider" enabled="true" cacheRolesInCookie="true">
  <providers>
    <clear />
    <add name="DziennikRoleProvider" type="Dziennik_MVC.Helpers.DziennikMembershipProvider, Dziennik_MVC" connectionStringName="EFDbContext" />
  </providers>
</roleManager>

回答1:

You have to setup the bindings before you inject the Providers.

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IUnitOfWork>().To<EFContext>().InRequestScope();
    kernel.Bind<IUzytkownicyRepository>().To<UzytkownicyRepository>().InRequestScope();

    kernel.Inject(Membership.Provider);
    kernel.Inject(Roles.Provider);
}


回答2:

I had the same problem. My solution was to change the repository method to be Public. Ninject cannot inject into a private property.