I'm using Autofac with ASP.NET MVC so all my controllers have their dependencies resolved nicely. But I have a custom membership provider with two dependencies. I suspect that the code to instantiate the membership provider is deep in ASP.NET, miles away from Autofac.
Is there a way to get Autofac to resolve my custom membership provider?
I assume that calling something like .Resolve
Here is the membership provider and its constructor :
public class MongoDBMembershipProvider : MembershipProvider
{
private IEmailService m_oEmailService;
private IUserRepository m_oUsers;
public MongoDBMembershipProvider() {
}
public MongoDBMembershipProvider( IEmailService oEmailservice, IUserRepository oUserRepository) {
m_oEmailService = oEmailservice;
m_oUsers = oUserRepository;
}
public override void Initialize( string name, NameValueCollection config) {
//TODO: Let Autofac do this work... how?
m_oEmailService = new EmailService();
开发者_StackOverflow中文版 m_oUsers = new Users();
}
public override bool ValidateUser( string sUsername, string sPassword) {
return m_oUsers.ValidateAttemptedLogon( sUsername, sPassword);
}
public override string GetUserNameByEmail( string sEmailAddress) {
return m_oUsers.GetUsernameByEmail( sEmailAddress);
}
}
I blogged about how to apply IoC to providers with Windsor. The concept itself is portable to any IoC container, the code is pretty trivial, and it enables the full capabilities of the container.
Even though asp.net membership providers are static, you can still wrap them in an interface. The one that I have been using is here:
http://gpsnerd.codeplex.com/SourceControl/changeset/view/03279dbfcef5#Infrastructure%2fMembership%2fIMembershipService.cs
You would then create an implementation of this interface that uses the asp.net membership. Then you can let your ioc bind this interface to the implementation. By extracting out this interface, now you can test your code using a fake.
bob
here's my guess...
first of all, delete your initialize method you shouldn't need it.
var builder = new ContainerBuilder();
builder.Register<EmailService>().As<IEmailService>();
builder.Register<Users>().As<IUserRepository>();
builder.Register<MongoDBMembershipProvider>().As<MembershipProvider>();
//something like this
MembershipProvider provider;
using (var container = builder.Build())
{
provider = container.Resolve<MembershipProvider>();
}
everyone else here has told you some ideas of how to get it into the runtime i think...
I think you are correct in that the membership provider is instantiated deep within ASP.NET. I think it would be easiest to just remove the interfaces from your constructor and call Resolve (or whatever the appropriate Autofac method is) to resolve your dependencies.
精彩评论