views:

29

answers:

1

I am building an asp.net MVC2 web app using StructureMap. I have created a custom MembershipProvider. I get it properly initialized at startup by calling:

x.For<MembershipProvider>().Use(Membership.Provider);
x.For<IMembershipProvider>().Use<CPOPMembershipProvider>();

In Initialize(), I am thinking of instantiating a repository to use for access to User data in the database.

So, I put in a private property in my custom MembershipProvider:

private IUserRepository userRepository;

And, inside Initialize(), I call:

IUserRepository userRepository = ObjectFactory.GetInstance<IUserRepository>();

First, is it "good practice" to instantiate a repository in my custom MembershipProvider?

Second, when I implement it, it seems like I can't access any StructureMap configuration that was properly setup in global.asax. When I call Debug.WriteLine(ObjectFactory.WhatDoIHave()) just before the above GetInstance() line, none of the configuration data is present (which I do see from the same Debug line placed in global.asax) and I get a "No Default Instance defined for PluginFamily CPOP.Domain.Contracts.Repositories.IUserRepository" error when calling GetInstance(). Why is that? Seems like I have a whole different container inside MembershipProvider.

A: 

Ended up using setter injection in StructureMap. The userRepository property in the custom MembershipProvider can be configured by calling:

CPOPMembershipProvider member =
     (CPOPMembershipProvider) Membership.Providers["CPOPMembershipProvider"];
ObjectFactory.Configure(x =>
{
    ...
    x.For<MembershipProvider>().Use(Membership.Provider);
    x.For<IMembershipProvider>().TheDefault.Is.Object(member);
    ...
    x.For<IPatientRepository>().Use<PatientRepository>();
    x.For<IUserRepository>().Use<UserRepository>();
    x.SetAllProperties(y => { y.OfType<IUserRepository>(); });
    ...
}); 

And, then calling BuildUp() on a target instance. I do this in Application_Start(), after all the registries have been called and StructureMap has all the configuration data.

ObjectFactory.BuildUp(Membership.Providers["CPOPMembershipProvider"]);

Done.

alphadogg