0

This is similar to Dependency Injection with Custom Membership Provider, but the responses there don't solve the issue for me.

I have a custom membership provider which has a dependency to a repository class. ASP.NET will always instantiate this using the parameter-less constructor, so to resolve the dependency to the repository I have a kind of service locator method ... my ctor looks like this:

public CustomMembershipProvider()
{
    _userRepository = AppStart_NinjectMVC3.Resolve<IUserRepository>();
}

And that Resolve method looks like this..

public static T Resolve<T>() where T : class
{
    return _kernel.Get<T>();
}

This works fine when I run the web app, because _kernel is correctly setup. However, I need to test the methods on my membership provider.. So when my test code tries to invoke the methods on membership provider it will instantiate a new membership provider class with the paramter-less ctor, which errors because _kernel is not setup.

What I want to do is somehow inject my FakeUserRepository class instead, but how can I achieve that?

Community
  • 1
  • 1
Matt Roberts
  • 26,371
  • 31
  • 103
  • 180

2 Answers2

1

I think I have a work round for this...

I've added a ctor to the membership provider which accepts a repository instance, and then I've manually instantiated my membership provider in my test class like this:

var prov = new CableSenseMembershipProvider(new FakeUserRepository());
        var config = new NameValueCollection();
        config.Add("applicationName", "ddd");
        config.Add("name", "CustomMembershipProvider");
        config.Add("requiresQuestionAndAnswer", "false");
        config.Add("requiresUniqueEmail", "false");
        prov.Initialize(config["name"], config);

Once I've dont this I can then invoke that instance and not worry about the parameter-less ctor being called.

As an aside, you still need to add the membership section to your test project app.config or it wont work - which is somewhat confusing!

Matt Roberts
  • 26,371
  • 31
  • 103
  • 180
1

Why not extract everything out of your custom membership provider into an implementation class and instantiate that class via the service locator then pass all your calls through to that? The implementation class can then be unit-testable and the ugly Membership stuff can be 'right by inspection'.

JeffreyABecker
  • 2,724
  • 1
  • 25
  • 36