Register a Singleton in Shell with Unity

Topics: Prism v2 - WPF 4
Oct 12, 2010 at 2:41 PM

I need to register some globally-available services with Unity. They are all Singleton objects. Is it a good way to register them in the Shell? If so, how can I get the reference of the Unity instance? If I can't, what’s the appropriate Unity API to do it?

Oct 12, 2010 at 3:30 PM

Hi,

First of all take into account that if you need a service that can be used from other modules, it is not necessary to register this in the Shell. For example, it might be registered from the Module Initializer class of a ModuleX in the container, so the service will be available from everywhere you have access to your container.

In Prism there is a documentation section about Communication, so you could take a look at this: Communication, see the Shared Services section.

Regarding to how to get a reference of the unity container, you could use the Dependency Injection mechanism of your choose (Constructor Injection, Dependency Property, etc), since the container is registered in the container. So your code might similar to the following (pseudo-code):

public ModuleX (IUnityContainer _container)
{
...
}

For more information you could check the following documentation section: Dependency Injection with Unity

Unity provide Lifetime Managers to provide a singleton instance of a particular class. So when you register your type, it might be similar to the following code:

_container.RegisterType<IMarketFeedService, MarketFeedService>(new ContainerControlledLifetimeManager());

Fore more information about LifetimeManager you could take a look at the following documentation section: Using Lifetime Managers

Hope this helps.

Fernando Antivero
http://blogs.southworks.net/fantivero