views:

140

answers:

3

I'm developing a class library that will be used in a number of different web applications, and possibly even made available as an open source project. There are several points where I would like to use IoC, but I don't want consumers of the class library to have to use one particular implementation. What is the best way to design this library so that it has the benefits of IoC, but no dependencies on one IoC framework?

Specifically, this library contains ASP.NET MVC controllers that have dependencies on various service interfaces. I understand I can create an IoCControllerFactory, but I'm not sure if this is the best approach, since some users may not be able or want to use this in their application just to gain the functionality that my library provides.

A: 

If the number of dependencies is fairly small, you can just pass them in by the way of the constructor. That way your consumers have complete choice over how to construct your objects.

Properties/Setters or custom initialisation objects are alternative possibilities and cover other areas in the design spectrum.

David Schmitt
+3  A: 

Pass the property in the constructor for simple scenarios.

For more complexe cases, use a Ioc container interface, provide a default implementation, but make it simple enough so that it can be implemented with any contianer.

CommonServiceLocator is such kind of interface.


Edit :

I would push another design now that would make CommonServiceLocator useless, and would make the overall experience of your library users better :

You choose the Ioc container that has all the needed features for your internal library requirements, and you ILMerge it as internal so that your library users do not see it. Users don't have to know that the library is using a container.

You have then to provide two main extension points : Configuration - a way to provide custom implementation of the dependencies (eg. Logger...) Factories - if your library needs to instantiate users' object, provide a way to specify a factory so that your users can hook it. This way they can use their own container to instantiate and inject their objects.

I made two full blog posts about this design :

IOC Container, Go Hide

IOC Container, Go Hider (part 2)

Think Before Coding