# Monday, August 30, 2010

There still seems to be some confusion about what is Dependency Injection (DI) and what is a DI Container, so in this post I will try to sort it out as explicitly as possible.

DI is a set of principles and patterns that enable loose coupling.

That’s it; nothing else. Remember that old quote from p. 18 of Design Patterns?

Program to an interface; not an implementation.

This is the concern that DI addresses. The most useful DI pattern is Constructor Injection where we inject dependencies into consumers via their constructors. No container is required to do this.

The easiest way to build a DI-friendly application is to just use Constructor Injection all the way. Conversely, an application does not automatically become loosely coupled when we use a DI Container. Every time application code queries a container we have an instance of the Service Locator anti-pattern. The corollary leads to this variation of the Hollywood Principle:

Don’t call the container; it’ll call you.

A DI Container is a fantastic tool. It’s like a (motorized) mixer: you can whip cream by hand, but it’s easier with a mixer. On the other hand, without the cream the mixer is nothing. The same is true for a DI Container: to really be valuable, your code must employ Constructor Injection so that the container can auto-wire dependencies.

A well-designed application adheres to the Hollywood Principle for DI Containers: it doesn’t call the container. On the other hand, we can use the container to compose the application – or we can do it the hard way; this is called Poor Man’s DI. Here’s an example that uses Poor Man’s DI to compose a complete application graph in a console application:

private static void Main(string[] args)
{
    var msgWriter = new ConsoleMessageWriter();
    new CoalescingParserSelector(
        new IParser[]
        {
            new HelpParser(msgWriter),
            new WineInformationParser(
                new SqlWineRepository(),
                msgWriter)
        })
        .Parse(args)
        .CreateCommand()
        .Execute();
}

Notice how the nested structure of all the dependencies gives you an almost visual idea about the graph. What we have here is Constructor Injection all the way in.

CoalescingParserSelector’s constructor takes an IEnumerable<IParser> as input. Both HelpParser and WineInformationParser requires an IMessageWriter, and WineInformationParser also an IWineRepository. We even pull in types from different assemblies because SqlWineRepository is defined in the SQL Server-based data access assembly.

Another thing to notice is that the msgWriter variable is shared among two consumers. This is what a DI Container normally addresses with its ability to manage component lifetime. Although there’s not a DI Container in sight, we could certainly benefit from one. Let’s try to wire up the same graph using Unity (just for kicks):

private static void Main(string[] args)
{
    var container = new UnityContainer();
    container.RegisterType<IParser, WineInformationParser>("parser.info");
    container.RegisterType<IParser, HelpParser>("parser.help");
    container.RegisterType<IEnumerable<IParser>, IParser[]>();
 
    container.RegisterType<IParseService, CoalescingParserSelector>();
 
    container.RegisterType<IWineRepository, SqlWineRepository>();
    container.RegisterType<IMessageWriter, ConsoleMessageWriter>(
        new ContainerControlledLifetimeManager());
 
    container.Resolve<IParseService>()
        .Parse(args)
        .CreateCommand()
        .Execute();
    container.Dispose();
}

We are using Constructor Injection throughout, and most DI Containers (even Unity, but not MEF) natively understands that pattern. Consequently, this means that we can mostly just map interfaces to concrete types and the container will figure out the rest for us.

Notice that I’m using the Configure-Resolve-Release pattern described by Krzysztof Koźmic. First I configure the container, then I resolve the entire object graph, and lastly I dispose the container.

The main part of the application’s execution time will be spent within the Execute method, which is where all the real application code runs.

In this example I wire up a console application, but it just as well might be any other type of application. In a web application we just do a resolve per web request instead.

But wait! does that mean that we have to resolve the entire object graph of the application, even if we have dependencies that cannot be resolved at run-time? No, but that does not mean that you should pull from the container. Pull from an Abstract Factory instead.

Another question that is likely to arise is: what if I have dependencies that I rarely use? Must I wire these prematurely, even if they are expensive? No, you don’t have to do that either.

In conclusion: there is never any reason to query the container. Use a container to compose your object graph, but don’t rely on it by querying from it. Constructor Injection all the way enables most containers to auto-wire your application, and an Abstract Factory can be a dependency too.

posted on Monday, August 30, 2010 10:06:58 PM (Romance Daylight Time, UTC+02:00)  #    Comments [2] Trackback
# Wednesday, August 25, 2010

One of my Twitter followers who appears to be using AutoFixture recently asked me this:

So with the AutoMoqCustomization I feel like I should get Mocks with concrete types too (except the sut) - why am I wrong?

AutoFixture’s extention for auto-mocking with Moq was never meant as a general modification of behavior. Customizations extend the behavior of AutoFixture; they don’t change it. There’s a subtle difference. In any case, the auto-mocking customization was always meant as a fallback mechanism that would create Mocks for interfaces and abstract types because AutoFixture doesn’t know how to deal with those.

Apparently @ZeroBugBounce also want concrete classes to be issued as Mock instances, which is not quite the same thing; AutoFixture already has a strategy for that (it’s called ConstructorInvoker).

Nevertheless I decided to spike a little on this to see if I could get it working. It turns out I needed to open some of the auto-mocking classes a bit for extensibility (always a good thing), so the following doesn’t work with AutoFixture 2.0 beta 1, but will probably work with the RTW. Also please not that I’m reporting on a spike; I haven’t thoroughly tested all edge cases.

That said, the first thing we need to do is to remove AutoFixture’s default ConstructorInvoker that invokes the constructor of concrete classes. This is possible with this constructor overload:

public Fixture(DefaultRelays engineParts)

This takes as input a DefaultRelays instance, which is more or less just an IEnumerable<ISpecimenBuilder> (the basic building block of AutoFixture). We need to replace that with a filter that removes the ConstructorInvoker. Here’s a derived class that does that:

public class FilteringRelays : DefaultEngineParts
{
    private readonly Func<ISpecimenBuilder, bool> spec;
 
    public FilteringRelays(Func<ISpecimenBuilder, bool> specification)
    {
        if (specification == null)
        {
            throw new ArgumentNullException("specification");
        }
 
        this.spec = specification;
    }
 
    public override IEnumerator<ISpecimenBuilder> GetEnumerator()
    {
        var enumerator = base.GetEnumerator();
        while (enumerator.MoveNext())
        {
            if (this.spec(enumerator.Current))
            {
                yield return enumerator.Current;
            }
        }
    }
}

DefaultEngineParts already derive from DefaultRelays, so this enables us to use the overloaded constructor to remove the ConstructorInvoker by using these filtered relays:

Func<ISpecimenBuilder, bool> concreteFilter
    = sb => !(sb is ConstructorInvoker);
var relays = new FilteringRelays(concreteFilter);

The second thing we need to do is to tell the AutoMoqCustomization that it should Mock all types, not just interfaces and abstract classes. With the new (not in beta 1) overload of the constructor, we can now supply a Specification that determines which types should be mocked.:

Func<Type, bool> mockSpec = t => true;

We can now create the Fixture like this to get auto-mocking of all types:

var fixture = new Fixture(relays).Customize(
    new AutoMoqCustomization(new MockRelay(mockSpec)));

With this Fixture instance, we can now create concrete classes that are mocked. Here’s the full test that proves it:

[Fact]
public void CreateAnonymousMockOfConcreteType()
{
    // Fixture setup
    Func<ISpecimenBuilder, bool> concreteFilter
        = sb => !(sb is ConstructorInvoker);
    var relays = new FilteringRelays(concreteFilter);
 
    Func<Type, bool> mockSpec = t => true;
 
    var fixture = new Fixture(relays).Customize(
        new AutoMoqCustomization(new MockRelay(mockSpec)));
    // Exercise system
    var foo = fixture.CreateAnonymous<Foo>();
    foo.DoIt();
    // Verify outcome
    var fooTD = Mock.Get(foo);
    fooTD.Verify(f => f.DoIt());
    // Teardown
}

Foo is this concrete class:

public class Foo
{
    public virtual void DoIt()
    {
    }
}

Finally, a word of caution: this is a spike. It’s not fully tested and is bound to fail in certain cases: at least one case is when the type to be created is sealed. Since Moq can’t create a Mock of a sealed type, the above code will fail in that case. However, we can address this issue with some more sophisticated filters and Specifications. However, I will leave that up to the interested reader (or a later blog post).

All in all I think this provides an excellent glimpse of the degree of extensibility that is built into AutoFixture 2.0’s kernel.

posted on Wednesday, August 25, 2010 9:56:38 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, August 19, 2010

The new internal architecture of AutoFixture 2.0 enables some interesting features. One of these is that it becomes easy to extend AutoFixture to become an auto-mocking container.

Since I personally use Moq, the AutoFixture 2.0 .zip file includes a new assembly called Ploeh.AutoFixture.AutoMoq that includes an auto-mocking extension that uses Moq for Test Doubles.

Please note that AutoFixture in itself has no dependency on Moq. If you don’t want to use Moq, you can just ignore the Ploeh.AutoFixture.AutoMoq assembly.

Auto-mocking with AutoFixture does not have to use Moq. Although it only ships with Moq support, it is possible to write an auto-mocking extension for a different dynamic mock library.

To use it, you must first add a reference to Ploeh.AutoFixture.AutoMoq. You can now create your Fixture instance like this:

var fixture = new Fixture()
    .Customize(new AutoMoqCustomization());

What this does is that it adds a fallback mechanism to the fixture. If a type falls through the normal engine without being handled, the auto-mocking extension will check whether it is a request for an interface or abstract class. If this is so, it will relay the request to a request for a Mock of the same type.

A different part of the extension handles requests for Mocks, which ensures that the Mock will be created and returned.

Splitting up auto-mocking into a relay and a creational strategy for Mock objects proper also means that we can directly request a Mock if we would like that. Even better, we can use the built-in Freeze support to freeze a Mock, and it will also automatically freeze the auto-mocked instance as well (because the relay will ask for a Mock that turns out to be frozen).

Returning to the original frozen pizza example, we can now rewrite it like this:

[Fact]
public void AddWillPipeMapCorrectly()
{
    // Fixture setup
    var fixture = new Fixture()
        .Customize(new AutoMoqCustomization());
 
    var basket = fixture.Freeze<Basket>();
    var mapMock = fixture.Freeze<Mock<IPizzaMap>>();
 
    var pizza = fixture.CreateAnonymous<PizzaPresenter>();
 
    var sut = fixture.CreateAnonymous<BasketPresenter>();
    // Exercise system
    sut.Add(pizza);
    // Verify outcome
    mapMock.Verify(m => m.Pipe(pizza, basket.Add));
    // Teardown
}

Notice that we can simply freeze Mock<IPizzaMap> which also automatically freeze the IPizzaMap instance as well. When we later create the SUT by requesting an anonymous BasketPresenter, IPizzaMap is already frozen in the fixture, so the correct instance will be injected into the SUT.

This is similar to the behavior of the custom FreezeMoq extension method I previously described, but now this feature is baked in.

posted on Thursday, August 19, 2010 9:25:50 PM (Romance Daylight Time, UTC+02:00)  #    Comments [7] Trackback
# Monday, August 09, 2010

It gives me great pleasure to announce that AutoFixture 2.0 beta 1 is now available for download. Compared to version 1.1 AutoFixture 2.0 is implemented using a new and much more open and extensible engine that enables many interesting scenarios.

Despite the new engine and the vastly increased potential, the focus on version 2.0 has been to ensure that the current, known feature set was preserved.

What’s new?

While AutoFixture 2.0 introduces new features, this release is first and foremost an upgrade to a completely new internal architecture, so the number of new releases is limited. Never the less, the following new features are available in version 2.0:

There are still open feature requests for AutoFixture, so now that the new engine is in place I can again focus on implementing some of the features that were too difficult to address with the old engine.

Breaking changes

Version 2.0 introduces some breaking changes, although the fundamental API remains recognizable.

  • A lot of the original methods on Fixture are now extension methods on IFixture (a new interface). The methods include CreateAnonymous<T>, CreateMany<T> and many others, so you will need to include a using directive for Ploeh.AutoFixture to compile the unit test code.
  • CreateMany<T> still returns IEnumerable<T>, but the return value is much more consistently deferred. This means that in almost all cases you should instantly stabilize the sequence by converting it to a List<T>, an array or similar.
  • Several methods are now deprecated in favor of new methods with better names.

A few methods were also removed, but only those that were already deprecated in version 1.1.

Roadmap

The general availability of beta 1 of AutoFixture 2.0 marks the beginning of a trial period. If no new issues are reported within the next few weeks, a final version 2.0 will be released. If too many issues are reported, a new beta version may be necessary.

Please report any issues you find.

After the release of the final version 2.0 my plan is currently to focus on the Idioms project, although there are many other new features that might warrant my attention.

Blog posts about the new features will also follow soon.

posted on Monday, August 09, 2010 1:32:06 PM (Romance Daylight Time, UTC+02:00)  #    Comments [3] Trackback