Search code examples
c#unity-containerprism

How to register the same instance(= singleton) for 2 interfaces within a prism IContainerRegistry


I've a Prism app, with Unity to make dependency injection.

I've one class that has the following inheritance:

ISomeService --> ISomeMoreSpecializedService --> SomeMoreSpecializedService
  • ISomeService is used in some non-application-specific module.
  • ISomeMoreSpecializedService is extending this previous interface, adding some application-specific concept
  • SomeMoreSpecializedService is the only implementation that should be used in a specific software
  • (There is also an abstract implementation of ISomeService)

My specialized service looks like this:

public class SomeMoreSpecializedService : SomeService, ISomeMoreSpecializedService
{
    public SomeMoreSpecializedService(ISomeDependency dependency){
    }
}

I'm in a Prism Module:

public class MyModule : IModule
{
    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterSingleton<ISomeService, SomeMoreSpecializedService>();
        containerRegistry.RegisterSingleton<ISomeMoreSpecializedService, SomeMoreSpecializedService>();
    }

    public void OnInitialized(IContainerProvider containerProvider)
    {
    }
}

But my issue is that I receive then 2 different singleton. How should I do this?

Before I was building a new SomeMoreSpecializedService(), and then doing RegisterInstance. This worked until now, but now I've some dependency to inject.


Solution

  • With Unity, you do

    containerRegistry.RegisterSingleton<FactoryController>();
    containerRegistry.Register<IFactoryController, FactoryController>();
    containerRegistry.Register<IFactoryToken, FactoryController>();
    

    i.e. a ContainerControlledLifetimeManager for the type without any interfaces and then attach the type to two interfaces without specified lifetime manager.

    Unfortunately, the behavior of IContainerRegistry.Register and IContainerRegistry.RegisterSingleton is mostly undefined and they just leak the behavior of the underlying container. So this will work, unless Unity changes its behavior (which it did in the past) or you switch to another container.