Q:

Inject repository to custom membership provider with Ninject

I'm trying to inject a repository to a custom membership provider with ninject in MVC 3.
In MembershipProvider I have tried the following:
[Inject]
public ICustomerRepository _customerRepository{ get; set; }

And
[Inject]
public TUMembershipProvider(ICustomerRepository customerRepository)
{
    _customerRepository = customerRepository;
}

In my ninject module i tried the following:
Bind<MembershipProvider>().ToConstant(Membership.Provider);

None of the above works.
When i use(in global.asa)
kernel.Inject(Membership.Provider);

together with 
[Inject]
public ICustomerRepository _customerRepository{ get; set; }

it works, but i have no life cycle management and this will cause a "ISession is open" error from NHibernate, because the ISession is InRequestScope and the repository is not.

A:

You could use the approach @Remo Gloor outlines in his blog post on provider injection. It involves 3 steps:

Add [Inject]s to any properties on your provider you need injected (although the pattern he shows -- creating a very simple class whose only function is to be a receptable for property injection and forwards any requests to a real class implemented using constructor injection --  is well worth following)
public class MyMembershipProvider : SqlMembershipProvider
{
    [Inject]
    public SpecialUserProvider SpecialUserProvider { get;set;}
    ...

Create an initializer wrapper that implements IHttpModule which pulls the provider in, triggering its creation:-
public class ProviderInitializationHttpModule : IHttpModule
{
    public ProviderInitializationHttpModule(MembershipProvider membershipProvider)
    {
    }
...

Register the IHttpModule in your RegisterServices :-
kernel.Bind<IHttpModule>().To<ProviderInitializationHttpModule>();

there is no 4; Ninject does the rest - bootstrapping all registered IHttpModules including the one you added) during the startup sequence.

(Don't forget to read the comments on the blog post re lifetimes etc.)

Finally, if you're looking for something completely braindead direct that solves it neatly, try this @Remo Gloor answer instead

PS a great writeup on the whole mess is Provider is not a Pattern by @Mark Seemann. (and the oboligatory plug for his excellent book:- Dependency injection in .NET which will have you figuring this stuff out comfortably from first principles)

