Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton-like behavior with Dependency Injection

After doing some research on MEF I came across the CreationPolicy.Shared property which according to MSDN:

Specifies that a single shared instance of the associated ComposablePart will be created by the CompositionContainer and shared by all requestors.

Sounds good as long as I always ensure that one and only one container ever accesses the class that I export with this policy. So how do I go about ensuring that only one container ever accesses my exported type? Here is my scenario:

I have a Windows service that needs to tap into a singleton-like class for some in-memory data. The data is non-persistent so I want it to be freshly created whenever the service starts up but it serves no purpose once the service is stopped. Multiple threads in my service will need to read and write to this object in a thread-safe fashion so my initial plan was to inherit from ConcurrentDictionary to ensure thread safe operations against it.

The threads that will be tapping into this class all inherit from a single abstract base class, so is there a way to have this class (and only this class) import it from MEF and have this work the way I want?

thanks for any tips you may have, I'm newish to MEF so I'm still learning the ins and outs

like image 507
snappymcsnap Avatar asked Jun 15 '12 18:06

snappymcsnap


1 Answers

If it absolutely must be a singleton amongst different containers, you could use a private constructor and expose a static Instance property, as if it were a "classic" non-container-managed singleton. Then in the composition root, use ComposeExportedValue to register it with the container:

container.ComposeExportedValue(MySingleton.Instance);
like image 64
default.kramer Avatar answered Oct 19 '22 18:10

default.kramer