Thursday, July 1, 2010

Autofac Part 2 - Ordering, Keyed, Named & Metadata Registration

As promised we are going to look into registration ordering, keyed and name registration and registration with metadata.

Registration ordering
When you register something ordering are by default preserved, meaning that the last registration are returned when resolving.
var builder = new ContainerBuilder();
object inst1 = new object();
object inst2 = new object();
builder.RegisterInstance(inst1);
builder.RegisterInstance(inst2);
object resolved = builder.Build().Resolve<object>();
// Here resolved are the same instance as inst2
If you want another behavior it can be done the following way:
object inst1 = new object();
object inst2 = new object();
builder.RegisterInstance(inst1);
builder.RegisterInstance(inst2).PreserveExistingDefaults();
object resolved = builder.Build().Resolve<object>();
// Here resolved are the same instance as inst1
Named and keyed registration
Named and keyed registration are a very handy feature, which allow you to have multiple instances of the same object return if different situations. Here is an example for named registration:
string name = "object.registration";
var cb = new ContainerBuilder();
cb.RegisterType<object>().Named<object>(name);
var c = cb.Build();
object o1 = c.Resolve<object>(name);
// But this will fail unless an registration has been made without
// a name
o1 = c.Resolve<object>();
Keyed registration are basically done the same way:
object key = new object();
var cb = new ContainerBuilder();
cb.RegisterType<object>().Keyed<object>(key);
var c = cb.Build();
object o1 = c.Resolve<object>(key);
// But this will fail unless an registration has been made without
// a key
o1 = c.Resolve<object>();
You are free to mix normal, named and keyed registration as you want, which gives you a lot of flexibility.
Registration with metadata
Metadata allows you to place extra information alongside a registration.
var p1 = new KeyValuePair<string, object>("p1", "p1Value");
var p2 = new KeyValuePair<string, object>("p2", "p2Value");
var builder = new ContainerBuilder();
builder.RegisterType<object>()
    .WithMetadata(p1.Key, p1.Value)
    .WithMetadata(p2.Key, p2.Value);
var container = builder.Build();

Meta<object> objectWithMetadata = container.Resolve<Meta<object>>();
// The metadata can now be accessed through
// objectWithMetadata.Metadata
// The resolved instance can be accessed through
// objectWithMetadata.Value

In the next part I'll look into module registration and using the event handlers provided when registering and resolving.

No comments:

Post a Comment