Jon Onstott
Jon Onstott

Reputation: 13727

Do I need a single instance of the Unity container?

Sorry for this noob question. I'm beginning to use the Unity 2.0 container with Silverlight and am putting some singletons in it. For the singletons to work, do I need to have just one instance of the container in my application? I assume that making a new unity container instance whenever I want to look up my singletons will result in separate containers with separate singletons.

Thanks, -Jon

Upvotes: 4

Views: 1544

Answers (2)

George Polevoy
George Polevoy

Reputation: 7671

You need a single instance of a container to achieve singleton behaviour. Also you need to register your singleton classes with ContainerControlledLifetimeManager.

Upvotes: 10

Mark Seemann
Mark Seemann

Reputation: 233150

It's a little confusing, because when we refer to Singletons in DI terminology, we don't mean the same as the Singleton design pattern.

Basically, the Singleton Lifestyle behaves as a (pattern) Singleton within the same container, but if you create and use it from a new instance of the container, you will get a different instance.

You can say that the Singleton Lifetime is a locally scoped Singleton.

To summarize on container usage, you don't need a Singleton container, but you need a single container instance to use the Singleton Lifestyle.

To make matters more confusing, in Unity the Singleton lifestyle is called ContainerControlledLifetimeManager...

Upvotes: 9

Related Questions