Register one interface as an alias for another

Oct 13, 2010 at 5:50 PM

public interface IBase
  void DoSomething();

public interface IExtended : IBase
  void DoSomethingElse();

 I have a shared library which implements IBase and has other services which require IBase.  I also have another library which has IExtended declared and implements it.

It's important that when I ask for IBase *or* IExtended that I get the same instance regardless of which I ask for first.  There is no single convenient point I can use RegisterInstance, so is there a way to do this with RegisterType?




Feb 8, 2011 at 6:06 PM

This is actually pretty easy to do. The trick to remember is that, other than type mapping, all the configuration you do actually applies to the concrete class, not the interface. So the trick is to just register both interfaces to the same concrete class, then set the lifetime for that concrete class. So something like this will work:

container.RegisterType<IBase, BaseAndExtended>()
    .RegisterType<IExtended, BaseAndExtended>()
        new ContainerControlledLifetimeManager());

You could actually collapse that a little, and put the lifetime manager into one of the other RegisterType calls, but in this case I prefer to separate it out because I think it's clearer.