I am writing a API over the top of a COM object and you have to pass around the COM object into pretty much every type and static method that I write so that I can test each part of my API.
Now my question is do I have an overloaded method for the one that takes the COM object but pass the IoC resolved one instead to the other one instead, so that the users of the API don’t have to worry about passing in the COM object or should I remove the overloaded method and just resolve it with out the option to pass it in.
Bit hard to explain so here is an example;
Constuctor Example;
FooType(IComObject obj,string table) {}
FooType(string table) : this(Ioc.Resolve<IComObject>(), table) {}
or just
FooType(string table) : this(Ioc.Resolve<IComObject>(), table) {}
Static method example;
public static SomeType Create(IComObject obj,string table)
{ // Do some work with obj}
public static SomeType Create(string table)
{
return MyClass.Create(Ioc.Resolve<IComObject>(),table);
}
or just
public static SomeType Create(string table)
{
IComObject obj = Ioc.Resolve<IComObject>();
return MyClass.Create(Ioc.Resolve<IComObject>(),table);
}
My biggest worry with the overloading is that it’s going to create a lot of methods that just froward calls. What other options do I have here or is this correct way of tackling this?
P.S I really don’t want to burden the user with having to pass a instance of IComObject all around their application.
One of the principles of Dependency Injection is that dependencies of a class should be made explicit to the outside world. When a class resolves a dependency itself (as in your second example) it goes against that principle, and is headed back down the road of using singleton services – though admittedly you are somewhat better off because you do have the IoC container as an “escape hatch” for mocking the service objects.
Obviously having a whole load of parameters in the constructors of all your objects is rather burdensome, but that’s where the IoC Container steps in. If it supports auto-wiring, and you’re using it as it was designed, you usually find yourself having to resolve very few instances yourself: you pull the first object out, and it comes ready-configured with all its dependencies – and they’re ready configured with all their dependencies, and so on. For this reason, Joshua Flanagan makes the argument that IoC Containers really ought to be called IoC Composers.
If you want to avoid burdening the users of your API, how about having a focal object that wraps up your IoC container and pulls configured instances out of it for consumption by calling code?