# Wednesday, January 27, 2010

AutoFixture 1.0 is now available on the CodePlex site! Compared to Release Candidate 2 there are no changes.

The 1.0 release page has more details about this particular release, but essentially this is RC2 promoted to release status.

It's been almost a year since I started development on AutoFixture and I must say that it has been an exciting and fulfilling experience! The API has evolved, but has turned out to be surprisingly flexible, yet robust. I even had some positive surprises along the way as it dawned on me that I could do new fancy things I hadn't originally considered.

If you use the Likeness feature (of which I have yet to write), you will run into this bug in Visual Studio. The bug is only in IntelliSense, so any code using Likeness will compile and work just fine.

While this release marks the end of AutoFixture's initial days, it also marks the beginning of AutoFixture 2.0. I already have lots of plans for making it even more extensible and powerful, as well as plans for utility libraries that integrate with, say, Moq or Rhino Mocks. It's going to be an exciting new voyage!

posted on Wednesday, January 27, 2010 11:54:58 PM (Romance Standard Time, UTC+01:00)  #    Comments [4] Trackback

In a reaction to Uncle Bob's recent post on Dependency Injection Inversion, Colin Decker writes that he doesn't consider the use of the single Guice @Inject annotation particularly problematic. As I read it, the central argument is that

annotations are not code. By themselves, they do nothing.

I'll have to take that at face value, but if we translate this reasoning to .NET it certainly holds true. Attributes don't do anything by themselves.

I'm not aware of any DI Container for .NET that requires us to sprinkle attributes all over our code to work (I don't consider MEF a DI Container), but for the sake of argument, let's assume that such a container exists (let's call it Needle). Would it be so bad if we had to liberally apply the Needle [Inject] attribute in large parts of our code bases?

Colin suggests no. As usual, my position is that it depends, but in most cases I would consider it bad.

If Needle is implemented like most libraries, InjectAttribute is just one of many types that make up the entire API. Other types would include NeedleContainer and its associated classes.

Java annotations may work differently, but in .NET we need to reference a library to apply one of its attributes. To apply the [Inject] attribute, we would have to reference Needle, and herein lies the problem.

Once Needle is referenced, it becomes much easier for a junior developer to accidentally start directly using other parts of the Needle API. Particularly he or she may start using Needle as a Service Locator. When that happens, Needle is no longer a passive participant of the code, but a very active one, and it becomes much harder to separate the code from the Container.

To paraphrase Uncle Bob: I don't want to write a Needle application.

We can't even protect ourselves from accidental usage by writing a convention-based unit test that fails if Needle is referenced by our code, because it must be referenced for the [Inject] attribute to be applied.

The point is that the attribute drags in a reference to the entire container, which in my opinion is a bad thing.

So when would it be less problematic?

If Needle was implemented in such a way that InjectAttribute was defined in an assembly that only contains that one type, and the rest of Needle was implemented in a different assembly, the attribute wouldn't drag the rest of the container along.

Whether this whole analysis makes sense at all in Java, and whether Guice is implemented like that, I can't say, but in most cases I would consider even a single attribute to be unacceptable pollution of my code base.

posted on Wednesday, January 27, 2010 8:36:34 PM (Romance Standard Time, UTC+01:00)  #    Comments [3] Trackback
# Tuesday, January 26, 2010

Reacting to my previous post, Krzysztof Koźmic was so kind to point out to me that I really should be using an IWindsorInstaller instead of writing the registration code in a static helper method (it did make me cringe a bit).

As it turns out, IWindsorInstaller is not a particularly well-described feature of Castle Windsor, so here's a quick introduction. Fortunately, it is very easy to understand.

The idea is simply to package configuration code in reusable modules (just like the Guice modules from Uncle Bob's post).

Refactoring the bootstrap code from my previous post, I can now move all the container configuration code into a reusable module:

public class BillingContainerInstaller : IWindsorInstaller

{

    #region IWindsorInstaller Members

 

    public void Install(IWindsorContainer container,

        IConfigurationStore store)

    {

        container.AddComponent<TransactionLog,

            DatabaseTransactionLog>();

        container.AddComponent<CreditCardProcessor,

            MyCreditCardProcessor>();

        container.AddComponent<BillingService>();

    }

 

    #endregion

}

While I was at it, I also changed from the fluent registration API to the generic registration methods as I didn't really need the full API, but I could have left it as it was.

BillingContainerInstaller implements IWindsorInstaller, and I can now configure my container instance like this:

var container = new WindsorContainer();

container.Install(new BillingContainerInstaller());

The Install method takes a parameter array of IWindsorInstaller instances, so you can pass as many as you'd like.

posted on Tuesday, January 26, 2010 8:24:51 PM (Romance Standard Time, UTC+01:00)  #    Comments [15] Trackback
# Monday, January 25, 2010

About a week ago Uncle Bob published a post on Dependency Injection Inversion that caused quite a stir in the tiny part of the .NET community I usually pretend to hang out with. Twitter was alive with much debate, but Ayende seems to sum up the .NET DI community's sentiment pretty well:

if this is a typical example of IoC usage in the Java world, then [Uncle Bob] should peek over the fence to see how IoC is commonly implemented in the .Net space

Despite having initially left a more or less positive note to Uncle Bob's post, after having re-read it carefully, I am beginning to think the same, but instead of just telling everyone how much greener the grass is on the .NET side, let me show you.

First of all, let's translate Uncle Bob's BillingService to C#:

public class BillingService

{

    private readonly CreditCardProcessor processor;

    private readonly TransactionLog transactionLog;

 

    public BillingService(CreditCardProcessor processor,

        TransactionLog transactionLog)

    {

        if (processor == null)

        {

            throw new ArgumentNullException("processor");

        }

        if (transactionLog == null)

        {

            throw new ArgumentNullException("transactionLog");

        }

 

        this.processor = processor;

        this.transactionLog = transactionLog;

    }

 

    public void ProcessCharge(int amount, string id)

    {

        var approval = this.processor.Approve(amount, id);

        this.transactionLog.Log(string.Format(

            "Transaction by {0} for {1} {2}", id, amount,

            this.GetApprovalCode(approval)));

    }

 

    private string GetApprovalCode(bool approval)

    {

        return approval ? "approved" : "denied";

    }

}

It's nice how easy it is to translate Java code to C#, but apart from casing and other minor deviations, let's focus on the main difference. I've added Guard Clauses to protect the injected dependencies against null values as I consider this an essential and required part of Constructor Injection – I think Uncle Bob should have added those as well, but he might have omitted them for brevity.

If you disregard the Guard Clauses, the C# version is a logical line of code shorter than the Java version because it has no DI attribute like Guice's @Inject.

Does this mean that we can't do DI with the C# version of BillingService? Uncle Bob seems to imply that we can do Dependency Inversion, but not Dependency Injection - or is it the other way around? I can't really make head or tails of that part of the post…

The interesting part is that in .NET, there's no difference! We can use DI Containers with the BillingService without sprinkling DI attributes all over our code base. The BillingService class has no reference to any DI Container.

It does, however, use the central DI pattern Constructor Injection. .NET DI Containers know all about this pattern, and with .NET's static type system they know all they need to know to wire dependencies up correctly. (I thought that Java had a static type system as well, but perhaps I am mistaken.) The .NET DI Containers will figure it out for you – you don't have to explicitly tell them how to invoke a constructor with two parameters.

We can write an entire application by using Constructor Injection and stacking dependencies without ever referencing a container!

Like the Lean concept of the Last Responsible Moment, we can wait until the application's entry point to decide how we will wire up the dependencies.

As Uncle Bob suggests, we can use Poor Man's DI and manually create the dependencies directly in Main, but as Ayende correctly observes, that only looks like an attractive alternative because the example is so simple. For complex dependency graphs, a DI Container is a much better choice.

With the C# version of BillingService, which DI Container must we select?

It doesn't matter: we can choose whichever one we would like because we have been following patterns instead of using a framework.

Here's an example of an implementation of Main using Castle Windsor:

public static void Main(string[] args)

{

    var container = new WindsorContainer();

    Program.Configure(container);

 

    var billingService =

        container.Resolve<BillingService>();

    billingService.ProcessCharge(2034, "Bob");

}

This looks a lot like Uncle Bob's first Guice example, but instead of injecting a BillingModule into the container, we can configure it inline or in a helper method:

private static void Configure(WindsorContainer container)

{

    container.Register(Component

        .For<TransactionLog>()

        .ImplementedBy<DatabaseTransactionLog>());

    container.Register(Component

        .For<CreditCardProcessor>()

        .ImplementedBy<MyCreditCardProcessor>());

    container.Register(Component.For<BillingService>());

}

This corresponds more or less to the Guice-specific BillingModule, although Windsor also requires us to register the concrete BillingService as a component (this last step varies a bit from DI Container to DI Container – it is, for example, redundant in Unity).

Imagine that in the future we want to rewire this program to use a different DI Container. The only piece of code we need to change is this Composition Root. We need to change the container declaration and configuration and then we are ready to use a different DI Container.

The bottom line is that Uncle Bob's Dependency Injection Inversion is redundant in .NET. Just use a few well-known design patterns and principles and you can write entire applications with DI-friendly, DI-agnostic code bases.

I recently posted a first take on guidelines for writing DI-agnostic code. I plan to evolve these guiding principles and make them a part of my upcoming book.

posted on Monday, January 25, 2010 9:48:27 PM (Romance Standard Time, UTC+01:00)  #    Comments [6] Trackback
# Wednesday, January 20, 2010

AutoFixture 1.0 Release Candidate 2 is now available on the CodePlex site! Compared to Release Candidate 1 there are very few changes, but the test period uncovered the need for a few extra methods on a recent addition to the library. RC2 contains these additional methods.

This resets the clock for the Release Candidate trial period. Key users have a chance to veto this release until a week from now. If no-one complains within that period, we will promote RC2 to version 1.0.

The RC2 release page has more details about this particular release.

posted on Wednesday, January 20, 2010 11:59:39 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

My previous post led to this comment by Phil Haack:

Your LazyOrderShipper directly instantiates an OrderShipper. What about the dependencies that OrderShipper might require? What if those dependencies are costly?

I didn't want to make my original example more complex than necessary to get the point across, so I admit that I made it a bit simpler than I might have liked. However, the issue is easily solved by enabling DI for the LazyOrderShipper itself.

As always, when the dependency's lifetime may be shorter than the consumer, the solution is to inject (via the constructor!) an Abstract Factory, as this modification of LazyOrderShipper shows:

public class LazyOrderShipper2 : IOrderShipper
{
    private readonly IOrderShipperFactory factory;
    private IOrderShipper shipper;
 
    public LazyOrderShipper2(IOrderShipperFactory factory)
    {
        if (factory == null)
        {
            throw new ArgumentNullException("factory");
        }
 
        this.factory = factory;
    }
 
    #region IOrderShipper Members
 
    public void Ship(Order order)
    {
        if (this.shipper == null)
        {
            this.shipper = this.factory.Create();
        }
        this.shipper.Ship(order);
    }
 
    #endregion
}

But, doesn't that reintroduce the OrderShipperFactory that I earlier claimed was a bad design?

No, it doesn't, because this IOrderShipperFactory doesn't rely on static configuration. The other point is that while we do have an IOrderShipperFactory, the original design of OrderProcessor is unchanged (and thus blissfully unaware of the existence of this Abstract Factory).

The lifetime of the various dependencies is completely decoupled from the components themselves, and this is as it should be with DI.

This version of LazyOrderShipper is more reusable because it doesn't rely on any particular implementation of OrderShipper – it can Lazily create any IOrderShipper.

posted on Wednesday, January 20, 2010 7:08:36 PM (Romance Standard Time, UTC+01:00)  #    Comments [7] Trackback

Jeffrey Palermo recently posted a blog post titled Constructor over-injection anti-pattern – go read his post first if you want to be able to follow my arguments.

His point seems to be that Constructor Injection can be an anti-pattern if applied too much, particularly if a consumer doesn't need a particular dependency in the majority of cases.

The problem is illustrated in this little code snippet:

bool isValid = _validator.Validate(order);  
if (isValid) 
{
    _shipper.Ship(order);  
}

If the Validate method returns false often, the shipper dependency is never needed.

This, he argues, can lead to inefficiencies if the dependency is costly to create. It's not a good thing to require a costly dependency if you are not going to use it in a lot of cases.

That sounds like a reasonable statement, but is it really? And is the proposed solution a good solution?

No, this isn't a reasonable statement, and the proposed solution isn't a good solution.

It would seem like there's a problem with Constructor Injection, but in reality the problem is that it is being used incorrectly and in too constrained a way.

The proposed solution is problematic because it involves tightly coupling the code to OrderShipperFactory. This is more or less a specialized application of the Service Locator anti-pattern.

Consumers of OrderProcessor have no static type information to warn them that they need to configure the OrderShipperFactory.CreationClosure static member - a completely unrelated type. This may technically work, but creates a very developer-unfriendly API. IntelliSense isn't going to be of much help here, because when you want to create an instance of OrderProcessor, it's not going to remind you that you need to statically configure OrderShipperFactory first. Enter lots of run-time exceptions.

Another issue is that he allows a concrete implementation of an interface to change the design of the OrderProcessor class - that's hardly in the spirit of the Liskov Substitution Principle. I consider this a strong design smell.

One of the commenters (Alwin) suggests instead injecting an IOrderShipperFactory. While this is a better option, it still suffers from letting a concrete implementation influence the design, but there's a better solution.

First of all we should realize that the whole case is a bit construed because although the IOrderShipper implementation may be expensive to create, there's no need to create a new instance for every OrderProcessor. Instead, we can use the so-called Singleton lifetime style where we share or reuse a single IOrderShipper instance between multiple OrderProcessor instances.

The beauty of this is that we can wait making that decision until we wire up the actual dependencies. If we have implementations of IOrderShipper that are inexpensive to create, we may still decide to create a new instance every time.

There may still be a corner case where a shared instance doesn't work for a particular implementation (perhaps because it's not thread-safe). In such cases, we can use Lazy loading to create a LazyOrderShipper like this (for clarity I've omitted making this implementation thread-safe, but that would be trivial to do):

public class LazyOrderShipper : IOrderShipper
{
    private OrderShipper shipper;
 
    #region IOrderShipper Members
 
    public void Ship(Order order)
    {
        if (this.shipper == null)
        {
            this.shipper = new OrderShipper();
        }
        this.shipper.Ship(order);
    }
 
    #endregion
}

Notice that this implementation of IOrderShipper only creates the expensive OrderShipper instance when it needs it.

Instead of directly injecting the expensive OrderShipper instance directly into OrderProcessor, we wrap it in the LazyOrderShipper class and inject that instead. The following test proves the point:

[TestMethod]
public void OrderProcessorIsFast()
{
    // Fixture setup
    var stopwatch = new Stopwatch();
    stopwatch.Start();
 
    var order = new Order();
 
    var validator = new Mock<IOrderValidator>();
    validator.Setup(v => 
        v.Validate(order)).Returns(false);
 
    var shipper = new LazyOrderShipper();
 
    var sut = new OrderProcessor(validator.Object,
        shipper);
    // Exercise system
    sut.Process(order);
    // Verify outcome
    stopwatch.Stop();
    Assert.IsTrue(stopwatch.Elapsed < 
        TimeSpan.FromMilliseconds(777));
    Console.WriteLine(stopwatch.Elapsed);
    // Teardown
}

This test is significantly faster than 777 milliseconds because the OrderShipper never comes into play. In fact, the stopwatch instance reports that the elapsed time was around 3 ms!

The bottom line is that Constructor Injection is not an anti-pattern. On the contrary, it is the most powerful DI pattern available, and you should think twice before deviating from it.

posted on Wednesday, January 20, 2010 5:28:03 PM (Romance Standard Time, UTC+01:00)  #    Comments [10] Trackback
# Wednesday, January 13, 2010

AutoFixture 1.0 Release Candidate 1 is now available on the CodePlex site! AutoFixture is now almost ten months old and has seen extensive use internally in Safewhere during most of this time. It has proven to be very stable, expressive and generally a delight to use.

If all goes well, the Release Candidate period will be short. Key users have a chance to veto the this version, but if no-one complains within a week from now, we will promote RC1 to version 1.0.

The RC1 release page has more detail about this particular release.

posted on Wednesday, January 13, 2010 11:48:13 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, January 04, 2010

In a previous post I described how AutoFixture's Do method can let you invoke commands on your SUT with Dummy values for the parameters you don't care about.

The Get method is the equivalent method you can use when the member you are invoking returns a value. In other words: if you want to call a method on your SUT to get a value, but you don't want the hassle of coming up with values you don't care about, you can let the Get method supply those values for you.

In today's example I will demonstrate a unit test that verifies the behavior of a custom ASP.NET MVC ModelBinder. If you don't know anything about ASP.NET MVC it doesn't really matter. The point is that a ModelBinder must implement the IModelBinder interface that defines a single method:

object BindModel(ControllerContext controllerContext,

    ModelBindingContext bindingContext);

In many cases we don't care about one or the other of these parameters, but we still need to supply them when unit testing.

The example is a bit more complex than some of my other sample code, but once in a while I like to provide you with slightly more realistic AutoFixture examples. Still, it's only 10 lines of code, but it looks like a lot more because I have wrapped several of the lines so that the code is still readable on small screens.

[TestMethod]

public void BindModelWillReturnCorrectResult()

{

    // Fixture setup

    var fixture = new Fixture();

    fixture.Customize<ControllerContext>(ob =>

        ob.OmitAutoProperties());

 

    var value = fixture.CreateAnonymous("Value");

    var bindingContext = new ModelBindingContext();

    bindingContext.ValueProvider =

        new Dictionary<string, ValueProviderResult>();

    bindingContext.ValueProvider["MyValue"] =

        new ValueProviderResult(value, value,

            CultureInfo.CurrentCulture);

 

    var expectedResult =

        new string(value.Reverse().ToArray());

    var sut = fixture.CreateAnonymous<MyModelBinder>();

    // Exercise system

    var result = fixture.Get((ControllerContext cc) =>

        sut.BindModel(cc, bindingContext));

    // Verify outcome

    Assert.AreEqual(expectedResult, result, "BindModel");

    // Teardown

}

The first part simply creates the Fixture object and customizes it to disable AutoProperties for all ControllerContext instances (otherwise we would have to set up a lot of Test Doubles for such properties as HttpContext, RequestContext etc.).

The next part of the test sets up a ModelBindingContext instance that will be used to exercise the SUT. In this test case, the bindingContext parameter of the BindModel method is important, so I explicitly set that up. On the other hand, I don't care about the controllerContext parameter in this test case, so I ask the Get method to take care of that for me:

var result = fixture.Get((ControllerContext cc) =>

    sut.BindModel(cc, bindingContext));

The Get method creates a Dummy value for the ControllerContext, whereas I can still use the outer variable bindingContext to call the BindModel method. The return value of the BindModel method is returned to the result variable by the Get method.

Like the Do methods, the Get methods are generic methods. The one invoked in this example has this signature:

public TResult Get<T, TResult>(Func<T, TResult> function);

There are also overloads that works with the versions of the Func delegate that takes two, three and four parameters.

As the Do methods, the Get methods are convenience methods that let you concentrate on writing the test code you care about while it takes care of all the rest. You could have written a slightly more complex version that didn't use Get but instead used the CreateAnonymous method to create an Anonymous Variable for the ControllerContext, but this way is slightly more succinct.

posted on Monday, January 04, 2010 9:53:24 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Sunday, December 20, 2009

I'll be doing a TechTalk on the Managed Extensibility Framework and Dependency Injection at Microsoft Denmark January 20th 2010.

The talk will be in Danish. Details and sign-up here.

posted on Sunday, December 20, 2009 8:56:33 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback