Ninject, injecting Membership.Provider in Register

2019-05-16 11:38发布

问题:

Anybody know how to configure Membership.Provider in RegisterServices of ninject initialization code?

In my code:

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        // Put additional bindings here
        kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>();
        kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
        kernel.Bind<IUserRepository>().To<UserRepository>();
        kernel.Bind<IRoleRepository>().To<RoleRepository>();
        kernel.Bind<ISecurityService>().To<SecurityService>();
        kernel.Inject(Membership.Provider);
        kernel.Inject(Roles.Provider);
    }

all modules are binded with the exception of kernel.Inject lines. I'm receiving the error: "This method cannot be called during the application's pre-start initialization stage".

The file is NinjectWebCommon of a standard nuget ninject.mvc installation. I'm trying to create a custom membership provider and injecting the service layer (SecurityService) in the provider.

Any help?

回答1:

I hit my head against the wall with this same issue, I finally found a relatively clean solution here.

The basic approach is:

  1. Use [Inject] attribute on any dependency properties in your custom membership provider class.

  2. Create a http module to resolve/inject your providers right away (Ninject 3 supports injecting HttpModules).

  3. Replace those last 2 inject statements in your RegisterServices() method with bindings for the provider and new HttpModule.

    kernel.Bind<MembershipProvider>().ToMethod(ctx => Membership.Provider); kernel.Bind<IHttpModule>().To<ProviderInitializationHttpModule>();