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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With