Overriding constructor parameters with Unity

An interesting feature of Castle Windsor is the ability to specify parameter overrides for a constructor using anonymous objects.

You define an anonymous object with properties named like the parameter you want to override and a value equal to the name you gave to a mapping. That means if you have a class with some dependencies like this one

public class MyService : IMyService
{
  public IFoo SomeFoo { get; set; }
  public MyService(IFoo someFoo)
  {
    this.SomeFoo = someFoo;
  }
}

and two classes that implement IFoo called Foo and Bar. Foo is registered as the default mapping (without a name) and Bar is registered as an additional mapping for IFoo with the name "Bar". Then you can use a ConfigurationBuilder and an anonymous object as in the snippet below

builder.For<IMyService>().Use<MyService>().Override(new { someFoo = "Bar" };

and the following test will pass green.*

//default mapping
builder.For<IFoo>().Use<Foo>();
//named mapping
builder.For<IFoo>().Add<Bar>().Named("Bar");
builder.For<IMyService>().Use<MyService>().Override(new { someFoo = "Bar" });
var service = container.Resolve<IMyService>() as MyService;

Assert.IsNotNull(service);
Assert.IsInstanceOfType(service.SomeFoo, typeof(Bar));

Neat.

*some of the infrastructure and setup code was omitted for brevity. See the full sample in TecX.Unity.Configuration.Test

Last edited Feb 20, 2012 at 11:09 AM by weberse, version 5

Comments

No comments yet.