views:

152

answers:

2

So say that I have type that takes some parameters in the constructor, like this:

public MyType(IComObject wrapper,string table) {}

now IComObject is a wrapper over a two different COM objects. All(90%) of my types have to use IComObject, so in good DI fashion (to allow for testing) I am passing IComObject into every type that needs it.

The main problem is that when someone goes to use my COM wrapper library that have to pass an instance of IComObject into everything they do which makes the code a little bit hard to manage and maintain.

I was wondering if I should use a IoC container or a global variable that the user can set so that they don't have to pass the IComOject instance around. Example:

public MyType(string table)
       : this(IoC.Resolve<IComObject>,table) {}

or

public MyType(string table)
   : this(StaticClass.ComInstance,table) {}

So that the user can do this:

//Set up Ioc container
COMObject object = new COMObject();
Ioc.Register(typeof(IComObject),object);
MyType mytype = new MyType("test.tab");

or

COMObject object = new COMObject();
StaticClass.ComInstance = object;
MyType mytype = new MyType("test.tab");

What do you think I should do in this situation?

A: 

Use a container, that's the point in them. I've only used StructureMap but I can definitely recommend it. Loads of docs, and its really easy to get up and running with. Once youre comfortable with working with it you'll love how easy it makes things. Decoupling for the win!

In reality, your container will be a static class that you query for objects, so there sort of isnt really a choice :)

Andrew Bullock
I was just worried about getting the user to have to worry about the setting up the IoC container.
Nathan W
+1  A: 

IoC is definitely the way to go. Globals aren't the worst evil in programming, and a small number of globals aren't the worst thing, but IoC is a nice, clean pattern that is well understood and easier to maintain in the long run. Dependencies are also more explicit with IoC.

Eddie