views:

609

answers:

2

I am dipping my toe into using a IoC framework and I have choosen to use Unity. One of the things that I still don't fully understand is how to resolve objects deeper into the application. I suspect I just haven't had the light bulb on moment that will make it clear.

So I am trying do something like the following in psuedo'ish code

void Workflow(IUnityContatiner contatiner, XPathNavigator someXml)
{
   testSuiteParser = container.Resolve<ITestSuiteParser>
   TestSuite testSuite = testSuiteParser.Parse(SomeXml) 
   // Do some mind blowing stuff here
}

So the testSuiteParser.Parse does the following

TestSuite Parse(XPathNavigator someXml)
{
    TestStuite testSuite = ??? // I want to get this from my Unity Container
    List<XPathNavigator> aListOfNodes = DoSomeThingToGetNodes(someXml)

    foreach (XPathNavigator blah in aListOfNodes)
    {
        //EDIT I want to get this from my Unity Container
        TestCase testCase = new TestCase() 
        testSuite.TestCase.Add(testCase);
    } 
}

I can see three options:

  1. Create a Singleton to store my unity container that I can access anywhere. I really am not a fan of this approach. Adding a dependency like that to use a dependency injection framework seems a little on the odd side.
  2. Pass the IUnityContainer to my TestSuiteParser class and every child of it (assume it is n levels deep or in reality about 3 levels deep). Passing IUnityContainer around everywhere just looks odd. I may just need to get over this.
  3. Have the light bulb moment on the right way to use Unity. Hoping someone can help flick the switch.

[EDIT] One of things that I wasn't clear on is that I want to create a new instance of test case for each iteration of the foreach statement. The example above needs to parse a test suite configuration and populate a collection of test case objects

+1  A: 

You should not really need to use your container directly in very many places of your application. You should take all your dependencies in the constructor and not reach them from your methods. You example could be something like this:

public class TestSuiteParser : ITestSuiteParser {
    private TestSuite testSuite;

    public TestSuitParser(TestSuit testSuite) {
        this.testSuite = testSuite;
    }

    TestSuite Parse(XPathNavigator someXml)
    {
        List<XPathNavigator> aListOfNodes = DoSomeThingToGetNodes(someXml)

        foreach (XPathNavigator blah in aListOfNodes)
        {
            //I don't understand what you are trying to do here?
            TestCase testCase = ??? // I want to get this from my Unity Container
            testSuite.TestCase.Add(testCase);
        } 
    }
}

And then you do it the same way all over the application. You will, of course, at some point have to resolve something. In asp.net mvc for example this place is in the controller factory. That is the factory that creates the controller. In this factory you will use your container to resolve the parameters for your controller. But this is only one place in the whole application (probably some more places when you do more advanced stuff).

There is also a nice project called CommonServiceLocator. This is a project that has a shared interface for all the popular ioc containers so that you don't have a dependency on a specific container.

Mattias Jakobsson
Thanks for the response. I have updated my question. Does this clarify for you?
btlog
@btlog Mark Seemann has that included in his answer. A common solution is to inject a factory for the testcase in the constructor of your TestSuiteParser class.
Mattias Jakobsson
+9  A: 

The correct approach to DI is to use Constructor Injection or another DI pattern (but Constructor Injection is the most common) to inject the dependencies into the consumer, irrespective of DI Container.

In your example, it looks like you require the dependencies TestSuite and TestCase, so your TestSuiteParser class should statically announce that it requires these dependencies by asking for them through its (only) constructor:

public class TestSuiteParser
{
    private readonly TestSuite testSuite;
    private readonly TestCase testCase;

    public TestSuiteParser(TestSuite testSuite, TestCase testCase)
    {
        if(testSuite == null)
        {
            throw new ArgumentNullException(testSuite);
        }
        if(testCase == null)
        {
            throw new ArgumentNullException(testCase);
        }

        this.testSuite = testSuite;
        this.testCase = testCase;
    }

    // ...
}

Notice how the combination of the readonly keyword and the Guard Clause protects the class' invariants, ensuring that the dependencies will be available to any successfully created instance of TestSuiteParser.

You can now implement the Parse method like this:

public TestSuite Parse(XPathNavigator someXml) 
{ 
    List<XPathNavigator> aListOfNodes = DoSomeThingToGetNodes(someXml) 

    foreach (XPathNavigator blah in aListOfNodes) 
    { 
        this.testSuite.TestCase.Add(this.testCase); 
    }  
} 

(however, I suspect that there may be more than one TestCase involved, in which case you may want to inject an Abstract Factory instead of a single TestCase.)

From your Composition Root, you can configure Unity (or any other container):

container.RegisterType<TestSuite, ConcreteTestSuite>();
container.RegisterType<TestCase, ConcreteTestCase>();
container.RegisterType<TestSuiteParser>();

var parser = container.Resolve<TestSuiteParser>();

When the container resolves TestSuiteParser, it understands the Constructor Injection pattern, so it Auto-Wires the instance with all its required dependencies.

Creating a Singleton container or passing the container around are just two variations of the Service Locator anti-pattern, so I wouldn't recommend that.

Mark Seemann
+1 For explaining my point better then me :)
Mattias Jakobsson
+1 for having the guile to call Fowlers work an anti-pattern!
Stimul8d