0
votes

I can't seem to figure out how to get dependency injection to work in a custom membership provider. I'm aware that the membership provider base class is managed deep in ASP.NET, but there should be some way to get dependency injection to work on private data members.

I'm using Unity and see this issue only in my membership and role providers

my issue is two fold:

  1. The application complains that it doesn't have a parameterless constructor for "MyMembershipProvider"
  2. even if I try this: https://stackoverflow.com/a/9815425/595335, security service is null in the ValidateUser method

     public class MyMembershipProvider : MembershipProvider
     {  
        public ISecurityService securityService;
    
        public MyMembershipProvider(ISecurityService securityService)
        {
        this.securityService = new SecurityService(); 
        }
    
        public override bool ValidateUser(string username, string password)
        {
             User user = securityService.GetUserByUsername(username);
    
             ...ommited...
    
        }
    
2

2 Answers

1
votes

It may not be as ideal, but you might need to use property injection instead of constructor injection.

1
votes

The problem is that your provider is created by a static class. Since static classes are not "instantiated" and live for the lifetime of the app, there is no way to allow your DI framework to instantiate a static class.

There are potential workarounds, but you can't use constructor injection. These workarounds are also brittle and overly complex. In short, it's a PITA and is just not worth the effort. You would probably save yourself a lot of headache by either forgettinga bout DI in a membership provider, or forgetting about using Membership and roll a custom IIdentity and IPrincipal solution.