Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm trying to learn implementing TDD with mocking/fake objects. One of the questions I have is how to initialize a dependency in an application which implements TDD? An example from this article Beginning Mocking With Moq 3 shows:

public class OrderWriter
{
    private readonly IFileWriter fileWriter;

    public OrderWriter(IFileWriter fileWriter)
    {
        this.fileWriter = fileWriter;
    }

    public void WriteOrder(Order order)
    {
        fileWriter.WriteLine(String.Format("{0},{1}", order.OrderId, order.OrderTotal));
    }
}

In this example, the constructor takes an IFileWriter parameter, I suppose because you want to supply the real file writer in case of the actual application, and the fake one for unit test. My question is, in the real application, who will supply this parameter? I suppose it will be the caller of this application. What if it has dependency as well in the constructor? Will the caller code be responsible for that too?

Maybe the better way is to use factory. How would this factory work? And how will the factory be distributed? Will it be in the constructor parameter like in the above manner?

share|improve this question

1 Answer 1

up vote 6 down vote accepted

What you're looking for is an IoC container to autowire all your objects at application startup. Take a look at Ninject, it has a very simple example on the front page. (It's also a good product and ... well, ninjas!)

As a general rule, you should attempt to resolve all of your top-level objects (eg. Page in ASP.NET, Controller in MVC for ASP.NET, Form in Winforms) directly from the IoC container and let it wire up ALL your dependencies through constructor injection. There will be times when you have to force it to resolve a lower-level item -- this is known as using it as a Service Locator -- but this should generally be avoided as they are tricky (but not impossible) to test, and create an API that can be confusing for the consumer, if that isn't you.

ASP.NET for MVC has, since v3, been specifically designed to abstract away the IoC container from the rest of your code while allowing you to auto-inject into any top-level class (Controller, View, Filter, etc) through the DependencyResolver class. Other .NET frameworks take a bit more effort, but it's possible if you Google around.

There is a book on the subject called Dependency Injection in .NET. I haven't read it personally, but I've heard good things.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.