Tuesday, 23 November 2010

How to Register Two Interfaces as a Singleton in Unity

Every now and then I find myself wanting to configure a single implementor for multiple interfaces in Unity. Say I have the following interfaces and I only want one instance of Foo, yet I want to be able to request either IFoo or IFoo2 from the container:

public interface IFoo

interface IFoo2 : IFoo

public class Foo : IFoo2

The way I would previously go about this is:

var foo = container.Resolve<Foo>();

This approach, works, but is less than ideal. First, it requites you to resolve something in the container, possibly before you have completely finished configuring the container (e.g. the dependencies of Foo might not be fully set up yet). Second, the container will dispose foo twice.

However, thanks to an answer from Sven K├╝nzler to a question on Stack Overflow, there is a much better way:

container.RegisterType<Foo>(new ContainerControlledLifetimeManager());
container.RegisterType<IFoo, Foo>();
container.RegisterType<IFoo2, Foo>();
Assert.AreSame(container.Resolve<IFoo>(), container.Resolve<IFoo2>());

You simply register the concrete type as a singleton, and then point as many interfaces at that type as you like.

1 comment:

Herit Shah said...

Mark, I need your very highly urgent help.
although the problem is very small, but only you & you have the answer.

if the thing works out, that freeware app is gonna distributed to whole india. so please contact me at contact@herit.co, i will then mail you over the stuff.
possibly it would be highly grateful if i can meet you over skype/msn.