Home / .NET / ASP.NET Provider dependency injection with Ninject 3.0.0

ASP.NET Provider dependency injection with Ninject 3.0.0



Unfortunately, ASP.NET providers like the MembershipProvider and RolesProvider aren’t designed for dependency injection. Many users have problems to assign dependencies to them. In this blog post I’ll show a way to how this can be done using Ninject.Web.Common 3.0.0. This solution works for MVC and WebForms.

The provider itself is created by the ASP.NET framework which adds the restriction that all dependencies have to be passed using property injection because the ASP.NET framework expects a parameter less constructor. So the first thing you have to do is to add a property for all required dependencies to your provider

    public class MyMembershipProvider : SqlMembershipProvider
    {
        [Inject]
        public SpecialUserProvider SpecialUserProvider
        {
            get; set;
        }

        public override bool ValidateUser(string username, string password)
        {
            return this.SpecialUserProvider.IsSpecialUser(username) ||
                   base.ValidateUser(username, password);
        }
    }

As second step you need to create an HttpModule that will get an instance of all your providers. The idea behind this is that the providers are resolved and injected long time before they are used somewhere else. In the following example it is done for the MembershipProvider only. But you can easily extend it to initialize all required providers.

    public class ProviderInitializationHttpModule : IHttpModule
    {
        public ProviderInitializationHttpModule(MembershipProvider membershipProvider)
        {
        }

        public void Init(HttpApplication context)
        {
        }

        public void Dispose()
        {
        }
    }

As last step you need to create the bindings for the http module and the providers.

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