My problem is a variation on this one: Unity Register two interfaces as one singleton
In my case the injected singleton component has two interfaces, but one of those interfaces is used to map multiple named concrete types.
For example, my Component requires as dependencies, a set of (named) IEventSources and a single IEventManager (which itself is also an IEventSource):
public interface IEventManager { }
public interface IEventSource { }
public class EventManager : IEventManager, IEventSource { }
public class EventSourceA : IEventSource { }
public class EventSourceB : IEventSource { }
public class Component
{
public Component(IEventManager eventManager, IEventSource[] eventSources)
{
Debug.Assert(eventSources.Contains((IEventSource) eventManager));
}
}
class Program
{
static void Main()
{
var container = new UnityContainer();
container.RegisterType<IEventManager, EventManager>(new ContainerControlledLifetimeManager());
container.RegisterType<IEventSource, EventManager>("EventManager", new ContainerControlledLifetimeManager());
container.RegisterType<IEventSource, EventSourceA>("EventSourceA");
container.RegisterType<IEventSource, EventSourceB>("EventSourceB");
container.RegisterType(typeof(Component));
container.Resolve<Component>();
}
}
Or, as I ultimately need to configure this from app.config:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="IEventManager" mapTo="EventManager">
<lifetime type="singleton" />
</register>
<register name="EventManager" type="IEventSource" mapTo="EventManager">
<lifetime type="singleton" />
</register>
<register name="EventSourceA" type="IEventSource" mapTo="EventSourceA" />
<register name="EventSourceB" type="IEventSource" mapTo="EventSourceB" />
<register type="Component" />
</container>
</unity>
Here two EventManager instances are created, and the assertion fails. I want to ensure that the same instance satisfies both Component dependencies.
I can have the component accept only the IEventSource instances, and at runtime pull out from that set the single IEventManager instance, but that seems brittle and smells bad to me. Is there a way to pull this off with Unity?