Singleton class with private constructor

Jan 21, 2009 at 2:50 PM
Edited Jan 21, 2009 at 2:51 PM
How do I set up my app.config to resolve a singleton class?

<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity>
    <containers>
      <container name="Default" >
       <types>
          <type type="Interfaces.IMySingleton, Interfaces"
                mapTo="Base.MySingleton, Base">
            <lifetime type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
               Microsoft.Practices.Unity" />
          </type>
        </types>
      </container>
    </containers>
  </unity>

The singleton's constuctors:
        private MySingleton() { }

        public static MySingleton Instance
        { get { return InternalInstance.Instance; } }

        private class InternalInstance
        {
            static InternalInstance() { }
            internal static readonly MySingleton Instance = new MySingleton();
        }


Thanks,
John
Jan 21, 2009 at 3:19 PM
You're encountering an error while resolving IMySingleton type, right?  Your MySingleton class should have a public constructor, this is a requirement in Unity 1.2.


Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.
entlib.support@avanade.com
Jan 24, 2009 at 8:03 AM
John,

Your question raised some interesting thoughts. Rather than try to cram them all into a post here, I put my response to your question on my blog. Please take a look and let me know if it helps.

-Chris