Tony Basallo
Tony Basallo

Reputation: 3074

Using a ServiceLocator in Class LIbraries and MVC DependencyResolver

I've really gotten into the DI/IoC things - it makes some things a lot easier. However, I have a few inherited classes that implement a class with a required parameterless constructor, I thus use a service locator to get what I want:

MyMembershipProivder() : MyMembershipProvider(ServiceLocator.Current.GetInstance<...>){}
MyMembershipProivder(IMemberRepo memberRepo){...}

Works perfect. However, since I'm also using MVC3 DependencyResolver I find myself no other way but to do:

var locator = new NinjectServiceLocator(kernel);
DependencyResolver.SetResolver(locator);
ServiceLocator.SetLocatorProvider(() => locator);

DependencyResolver gets used within the MVC app and the ServiceLocator gets used throughout the various class libraries.

Is this the ideal way to do this? Am I missing something?

Update

In the example above, the class is a custom asp.net mebership provider. The asp.net membership provider factory requires for my custom provider to have a parameterless constructor, forcing me to use the service locator to inject the repository that it uses internally.

Upvotes: 1

Views: 2236

Answers (2)

Linkgoron
Linkgoron

Reputation: 4870

It seems as if you don't really have a choice, unless you can refactor your application to use DI from the start. So, I guess using custom a Service Locator is your best bet.

Although, if the classes you've "inherited" are the controller classes you can just remove the default constructors and be done with it, as MVC will handle everything for you.

I've never seen the ServiceLocator class, is it this?

EDIT:

As I've said, I don't see that you have any other option for decoupling. Service location is probably your best bet, without introducing too much bloat and complexity.

Stuff that's implemented as something built into the .Net FW you should look for specific solutions like the one presented for the Membership Provider.

Upvotes: 0

Kalman Speier
Kalman Speier

Reputation: 1937

You don't need the parameterless constructor, the Dependency Resolver will inject your dependency into the constructor:

MyMembershipProivder(IMemberRepo memberRepo){...}

You can replace the default controller factory (to use parameterless constructors in your controllers):

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

You wont need to replace the default controller factory, see Linkgoron's comment below.

Anyway using the Dependency Resolver for your MVC application and the Service Locator for your class libraries is fine, I think.

Hope this helps.

Upvotes: 2

Related Questions