Unity container and interface inheritance

May 26, 2010 at 9:31 AM
i m using interface inheritance (to control which parts of class are exposed in different cases) what is the best way to register those interfaces in the container so that their class is singleton?
Developer
May 28, 2010 at 9:42 PM
Edited May 28, 2010 at 9:55 PM

Hi,

By default, the RegisterType method in the UnityContainer registers types for a transient lifetime, which means that a new instance will be created on each call to the Resolve method. If you want to register an interface mapping in the container, so that the concrete class that implements that interface is registered as a singleton instance, you have to include an instance of the ContainerControlledLifetimeManager in the RegisterType method.

The code for that would look like this:

myContainer.RegisterType<IMyService, CustomerService>(new ContainerControlledLifetimeManager());

You can find more information on the subject in this article.

I hope you find this helpful.

Guido Leandro Maliandi
http://blogs.southworks.net/gmaliandi

May 30, 2010 at 7:33 AM
yes i m familiar with the ContainerControlledLifetimeManager. i m using it all the time. so you are claiming that if i got an interface inheritance, e.g. : ...public interface IAppGlobalData : IAppGlobalDataCommon{} and i want to register both to the container pointing to the same class... the best way would be to go RegisterType<> twice??? like so: theContainer.RegisterType<IAppGlobalDataCommon, AppGlobalData>(new ContainerControlledLifetimeManager()); theContainer.RegisterType<IAppGlobalData, AppGlobalData>(new ContainerControlledLifetimeManager()); notice that both interfaces are pointing to the same class. right?
Developer
Jun 2, 2010 at 5:14 PM

Hi,

You approach seems correct. If you want to map both interfaces to the same implementation, you should call the RegisterType<T> method for each interface mapping, regardless of the fact that they inherit from each other.

As this is not strictly related to Prism, you may get better support in the Unity forum.

I hope you find this helpful.

Guido Leandro Maliandi
http://blogs.southworks.net/gmaliandi