2
votes

I'm working on an ASP.NET MVC3 application, which has a custom MembershipProvider to handle authentication. This provider has a dependency on a service called IUserService, which is being set by property injection.

public class MyMembershipProvider : MembershipProvider
{
    public IUserService UserService { get; set; }

    public override bool ValidateUser(string username, string password)
    {
        return UserService.IsValidLogon(username, password);
    }
}

I'm using Castle Windsor 3 to manage everything. In my application startup, I register the membership provider successfully:

protected void Application_Start()
{
    _container = new WindsorContainer().Install(FromAssembly.This());
    _container.Register(Component.For<MyMembershipProvider>().LifeStyle.Transient.Named("myProvider"));
}

but when the provider gets called, I get a null reference exception for the UserService property. How can I tell Castle Windsor to inject my property?

3

3 Answers

3
votes

ASP.NET does not delegate creation of Membership Provider to 3rd Parties(ie. You can not DI the MembershipProvider). This is one of the pain points of ASP.NET. The MembershipProvider instance created by ASP.NET can be accessed through Membership.Provider. You can do property injection on this.

1
votes

I've created a membership provider which breaks down the different responsibilities in smaller interfaces (which allows you to use DI). It's free and available as a nuget package

http://blog.gauffin.org/2011/09/a-more-structured-membershipprovider/

0
votes

As Eranga points out, you will have to manually inject the property the first time you access the MembershipProvider. Not much you can do about it, since the MembershipProvider loads it's instance deep in the bowels of asp.net.

I would suggest that you NOT use dependency injection with this, however. Since the Membership provider is a static class. It is created once per application, and thus the connection will stay open for the lifetime of the application pool.

For my custom provider, I usually just new up my instances so that connection lifetimes can be better maintained. It sucks, but I feel it's better than leaving a hanging connection laying around.