none
MEF How to create a cross process singleton RRS feed

  • Question

  • I have a client application that I want to share a common instance between invocations but I everything that I have tried end up with a new instance for each time it is run.

    I have simplified my problem as follows with the 3 projeccts in the one solution:

    // ClassLibrary: IServer.dll
    namespace IServer
    {
        public interface IServer
        {
            DateTime DateTimeCreated { get; }
        }
    }
    
    // ClassLibrary: Server.dll references IServer.dll
    namespace Server
    {
        [Export(typeof(IServer.IServer))]
        public class Server : IServer.IServer
        {
            public static DateTime _dateTimeCreated = DateTime.Now;
            public DateTime DateTimeCreated { get { return _dateTimeCreated; } }
        }
    }
    
    // ConsoleApplication: Client.dll references IServer.dll
    
       class Program
        {
            [Import(typeof(IServer.IServer))]
            public IServer.IServer _server;
            
            static void Main(string[] args)
            {
                Program p = new Program();
                p.Run();
            }
    
            void Run()
            {
                Compose();
                Console.WriteLine("Client.Server " + _server.DateTimeCreated.ToString());
                Console.ReadKey();
            }
            private void Compose()
            {
                CompositionContainer container = new CompositionContainer(
                    new DirectoryCatalog(@"D:\Projects\MEFExample 2\Server\bin\Debug"));
                container.ComposeParts(this);
            }
        }

    When I run Client.exe multiple times I get separate (not shared) Server _server objects. I want the same (singleton) instances shared.


    Mark Latham

    Monday, February 18, 2013 3:24 AM

Answers

All replies