Today I played a bit with Autofac, and I learned few simple but nice tricks. This blog post is for my personal notes. If you haven’t used Autofac or know little about IoC it might be of interest for you.
Below we have fun setup. I call it “fun”, because it is very explicit and easy to understand. Reading though it makes it clear what dependencies are:
builder
    .Register(b => new F())
    .As<IF>();

builder
    .Register(b => new E())
    .As<IE>();

builder
    .Register(b => new D1())
    .Named<ID>(SomeD1Name);

builder
    .Register(b => new D2())
    .Named<ID>(SomeD2Name);

builder
    .Register((b,prms) => new C(b.Resolve<IE>(), prms.TypedAs<IF>()))
    .Named<IC>(CName);

builder
    .Register((b,prms) => new B(b.Resolve<IF>(), b.ResolveNamed<IC>(CName, prms)))
    .As<IB>();

builder
    .Register(b => new A(b.Resolve<IE>(), 
        b.ResolveNamed<ID>(SomeD1Name),
        b.ResolveNamed<ID>(SomeD2Name)))
    .As<IA>(AName);

builder
    .Register(b => new Service(b.Resolve<IComponentContext>(),
        b.Resolve<IA>(), b.Resolve<IB>()))
    .As<IService>();

And that’s it.

I would like to pay your attention to few things. One of them is “prms.TypedAs”, which is great way to inject parameters for your construction later on. Another thing is passing IComponentContext to the Service instance. This two things altogether will allow you to resolve dependencies inside of your Service class, just like below (assuming you have field _componentContext):
_componentContext.Resolve<IB>(new TypedParameter(typeof(IF), new F1()));

As you understood this will create us instance of B, by passing into its constructor instance of F and instance of C, created basing on E and another implementation of IF, which is F1 (not one registered at very beginning). Isn’t it nice?
For serious reading on Autofac please refer to its web site: