Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity dependency injection in custom membership provider

I have ASP.NET MVC3 project where I want to use custom membership provider. Also I want to use Unity for resolving my dependency injection.

this is code from Global.asax:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        var container = new UnityContainer();
        container.RegisterType<IAuthentification, Authentification>();
        container.RegisterType<IRepository, Repository>();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

    }

this is code from my membership provider:

public class CustomMembershipProvider : MembershipProvider
{
   [Dependency]
   private IProveaRepository Repository { get; set; }

   public override bool ValidateUser(string username, string password)
    {
       .....
    }

Problem is when I put breakpoint to ValidateUser method I see that Repository property not initialized. But this construction:

   [Dependency]
   private IProveaRepository Repository { get; set; }

for example, works fine in controllers.

Does anybody know why it is so and what to do?

like image 942
justkolyan Avatar asked Jun 29 '11 10:06

justkolyan


1 Answers

I had the same problem over the last couple of days. I ended up with the following solution (type and field names changed to match yours).

public class CustomMembershipProvider : MembershipProvider       
{
    private IProveaRepository repository;

    public CustomMembershipProvider() 
        : this (DependencyResolver.Current.GetService<IProveaRepository>())
    { }

    public CustomMembershipProvider(IProveaRepository repository)
    {
        this.repository= repository;
    }

    public override bool ValidateUser(string username, string password)
    {
        ...
    }
}

So even though Unity is not in control of the building of the CustomMembershipProvider, the parameterless constructor gets Unity involed (via the MVC3 DependencyResolver) to supply the correct repository instance.

If you're unit testing the CustomMembershipProvider then you can just build an instance with Unity directly, which will use the second constructor and avoid the call to DependencyResolver.

like image 67
Andrew Cooper Avatar answered Oct 09 '22 12:10

Andrew Cooper