4

Hey it's my first post so I'm ask for understanding. I've looked many posts but I didn't find solution.

I want to implement custom membershiprovider class with:

namespace Mvc_car.Authorization 
{
public class SimpleMembershipProvider : MembershipProvider
{
    private NHibernateRepository<Uzytkownik> repo;

    ISession session;

    [Inject]
    public SimpleMembershipProvider(ISession session)
    {
        this.session = session;
    }

    public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
    {
        repo = new NHibernateRepository<Uzytkownik>(session);
        base.Initialize(name, config);
    }

my bindings:

kernel.Bind<ISession>().ToMethod(x => MvcApplication.SessionFactory.OpenSession()).InRequestScope();
kernel.Bind(typeof(IRepository<>)).To(typeof(NHibernateRepository<>));
kernel.Inject(Membership.Provider); //either with or without that

I've changed in web.config:

<membership defaultProvider="MyMembershipProvider">
  <providers>
    <clear/>
    <add name="MyMembershipProvider" type="Mvc_car.Authorization.SimpleMembershipProvider"/>
  </providers>
</membership>

after try of logging following error occurs:

This method cannot be called during the application's pre-start initialization stage.

Remo Gloor
  • 32,665
  • 4
  • 68
  • 98
caruso
  • 191
  • 10

1 Answers1

0

The solution to this is pretty simple. In your class containing the PreApplicationStartMethod attribute, add a static method like this.

 public static class NinjectWebCommon 
 {
        public static void InjectProviders()
        {
            Bootstrapper.Kernel.Inject(Membership.Provider);
            Bootstrapper.Kernel.Inject(Roles.Provider);
        }

    ...

 }

When setting up your Provider, dont inject the dependencies through the constructor. Instead decorate the properties with an [Inject] attribute like this.

public class DefaultMembershipProvider : MembershipProvider
{
    [Inject]
    public IUserRepository UserRepository { get; set; }
}

After that, its as simple as calling NinjectWebCommon.InjectProviders() from your global.asax Application_Start() method.

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        NinjectWebCommon.InjectProviders();
        ...
    }
}
Chris Lees
  • 2,140
  • 3
  • 21
  • 41