Inject repository to custom membership provider with Ninject

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

  1. 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;}
        ...
    
  2. Create an initializer wrapper that implements IHttpModule which pulls the provider in, triggering its creation:-

    public class ProviderInitializationHttpModule : IHttpModule
    {
        public ProviderInitializationHttpModule(MembershipProvider membershipProvider)
        {
        }
    ...
    
  3. Register the IHttpModule in your RegisterServices :-

    kernel.Bind<IHttpModule>().To<ProviderInitializationHttpModule>();
    
  4. 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)

Leave a Comment