Unity Container and double singleton

It turns out that after re-registering type as a singleton in Unity calls to container.Resolve() return a new instance. This may lead and have led to ugly bugs if your code relies on having only one instance of the type. Proofing test:

using NUnit.Framework;
using Unity;
using Unity.Lifetime;

namespace DoubleSingletonRegistration
{
    [TestFixture]
    public class DoubleSingletonTest
    {
        public class Foo {}

        [Test]
        public void NewInstanceReturnedAfterReregistration()
        {
            var container = new UnityContainer();

            container.RegisterType<Foo>(new ContainerControlledLifetimeManager());
            var foo1 = container.Resolve<Foo>();
            var foo2 = container.Resolve<Foo>();

            container.RegisterType<Foo>(new ContainerControlledLifetimeManager());
            var foo3 = container.Resolve<Foo>();
            var foo4 = container.Resolve<Foo>();

            Assert.AreSame(foo1, foo2);
            Assert.AreNotSame(foo2, foo3); // new instance returned after re-registration!
            Assert.AreSame(foo3, foo4);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *