RegisterInstance & Singleton

Nov 2, 2012 at 12:35 PM

 

This might be a newbie question, but i am wondering if we have to implement a singleton pattern on the object we are referencing with IUnityContainer.RegisterInstance.  As in the following code snippet, MessageService implement singleton design pattern.

excerpt from BootStrapper  :

IUnityContainer myContainer = new UnityContainer(); myContainer.RegisterInstance<IMessageService>(MessageService.Instance); myContainer.Resolve<IMessageService>(); return myContainer;

 

MessageService singleton pattern :

  public class MessageService : IMessageService
    {
        private static volatile MessageService instance;
        private static object syncRoot = new Object();

        private IMessageService _messageServiceCopy;

        private MessageService() { }

        public static MessageService Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new MessageService();
                    }
                }
                return instance;
            }
        }
    }

I noticed that the same object is returned even though i don't implement singleton pattern in the service but is it a good practice ?

Nov 4, 2012 at 10:27 PM

The reason you are seeing the same instance returned is that the default LifetimeManager when using RegisterInstance is ContainerControlledLifetimeManager (which is a singleton).

As in most design questions and decisions, the answer to whether you need to implement the singleton in code is that it depends.  Personally, if I'm using a container then I will let the container manage the lifetime of my objects (it's one of the things it's designed to do).  This gives flexibility going forward in changing the lifetime of the object.  For example, if later I decide I actually need a singleton but a singleton per request or for a custom "duration" then it is quite easy to change the lifetime manager to support this. 

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com