I have a method returning an ISomething. I am trying to use Inversion of Control throughout my program… but I have no idea how to do it when it comes to the return value – I cannot pass it to the method, or to the object when constructing it, because this method is supposed to create the object.
The only solution I see is to pass an ISomething factory (Func<ISomething>) to the object when constructing it. Is this the usual / correct solution or is something else recommended?
[Edit] Weird – nobody else had this problem? I mean, there’s no up- (or even down-) voting…
[Edit] More details: the method is supposed to import an IExcel into an ITable. The consensus below seems to be that I should think of this method as a converter, transforming an IExcel into an ITable, thus receiving both as arguments instead of returning the ITable value. I’ll leave this up for one more day and then go with one of the responses if nothing new shows up.
Is your method supposed to be constructing the ISomething, or setting it’s state and returning an ISomething with state initialized? (or does this need to be one operation?)
If your class has a method that is responsible for creating an ISomething, then it is an ISomethingFactory (unless you have mixed concerns). In that case, it has the logic to choose the correct ISomething implementation and create it, so you shouldn’t worry too much about the IoC aspect.
However, if this class’s concern is not creating the appropriate ISomething, then I would probably pass a factory in. The issue is, that in most cases your DI container should be able to do this for you (call a factory to get the appropriate ISomething), so seeing a method that must create an ISomething that is not a factory makes me nervous.
Trying to give architectural guidance is always tough in a forum like this though – but with the limited input there I’d say either you have a factory that you didn’t know was a factory, or you have a problem.