none
MEF singleton problem RRS feed

  • Question

  • Hi there

    Cannot accomplish the simple thing: import a singleton instance of the class to the places where it is needed.

    Here is my export declaration:

    [PartCreationPolicy(CreationPolicy.Shared)]
        [Export]
        public class SelfScheduleMainVM : BaseController, IBroadcasting
        {...

    In the class which needs it, there is an import declaration:

    [Import(RequiredCreationPolicy = CreationPolicy.Shared)]
            public SelfScheduleMainVM MainVM;

    and constractor of that class instantiates it:

    var catalog = new AggregateCatalog();
                catalog.Catalogs.Add(new AssemblyCatalog(typeof(SelfScheduleMainVM).Assembly));
                new CompositionContainer(catalog).ComposeParts(this);

    I got the instance of MainVM, but! It is the new instance, not the class which I need to be shared as a singleton.

    How to fix it?

    Thanks.

    Wednesday, February 26, 2014 4:03 PM

All replies

  • Hi Renziglov,

    Maybe you have some misunderstanding about MEF singleton. By default, MEF will always return the same instance of a class when it fill your imports. So technically you don’t have to do anything if you want it to be a singleton. This is what MEF calls a shared creation policy.

    For more information, see the following link. http://mef.codeplex.com/wikipage?title=Parts%20Lifetime.

    Hope useful.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, February 27, 2014 5:27 AM
    Moderator
  • Hi there

    >Maybe you have some misunderstanding about MEF singleton

    This may be. But regardless to my understanding, you can see code snippets above. When I compose parts, it always creates new instancies. I check the instance difference by the fact that the exported instance is fully populated, but imported one has all his members NULL (not initialized in constructor).

    Any clue?

    Thanks

    Friday, February 28, 2014 1:32 PM
  • Hi Renziglov,

    Can you please post some evidences or code to help us reproduce this problem?

    Thank you for understanding.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, March 3, 2014 8:04 AM
    Moderator