views:

131

answers:

1

I was using the default AspNetSqlMembershipProvider in my application. Authentication is performed via an AuthenticationService (since I'm also supporting other forms of membership like OpenID).

My AuthenticationService takes a MembershipProvider as a constructor parameter and I am injecting the dependency using StructureMap like so:

For<MembershipProvider>().Use(Membership.Provider);

This will use the MembershipProvider configured in web.config. All this works great.

However, now I have rolled my own MembershipProvider that makes use of a repository class. Since the MembershipProvider isn't exactly IoC friendly, I added the following code to the MembershipProvider.Initialize method:

_membershipRepository = ObjectFactory.GetInstance<IMembershipRepository>();

However, this raises an exception, like StructureMap hasn't been initialized (cannot get instance of IMembershipRepository). However, if I remove the code and put breakpoints at my MembershipProvider's initialize method and my StructureMap bootstrapper, it does appear that StructureMap is configured before the MembershipProvider is initialized.

My only workaround so far is to add the above code to each method in the MembershipProvider that needs the repository. This works fine, but I am curious as to why I can't get my instance in the Initialize method. Is the MembershipProvider performing some internal initialization that runs before any of my own application code does?

Thanks Ben

+1  A: 

Yes, the provider is initialized by the ASP.Net runtime when the AppDomain is spun up, far in advance of any execution of your code.

You will need to choose another point to do your composition, perhaps in Global.Application_???.

Sky Sanders
Thanks for the reply. I think I will continue to get my instances within each membership provider method, rather than changing my composition point - as everything else works okay - maybe we will get some DI friendly providers in .NET 5 :)
Ben
In my experience, the Initialize method of a memebership provider is called after app_start has fired, so IoC-enabling a membership provider isn't that hard. HealthMonitoring providers on the other hand... their initialize method seems to get called before app_start so they present some interesting challenges.
Paul Suart