ipjohnson / Grace

Grace is a feature rich dependency injection container library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Singleton Export bug

ulilaun opened this issue · comments

The following test should work in my opinion

[Fact]
        public void Export_Singleton()
        {
            var container = new DependencyInjectionContainer();

            container.Configure(c =>
            {
                c.Export<BasicService>().As<IBasicService>().Lifestyle.Singleton();
            });

            var interfaceService1 = container.Locate<IBasicService>();
            var interfaceService2 = container.Locate<IBasicService>();
            var typeService = container.Locate<BasicService>();

            Assert.IsType<BasicService>(interfaceService1);
            Assert.IsType<BasicService>(interfaceService2);
            Assert.IsType<BasicService>(typeService);
            Assert.Same(interfaceService1, interfaceService2);
            Assert.Same(interfaceService1, typeService);
        }

Best regards, Uli

The reason typeService is not the same instance is because it counts as two different registrations (key IBasicService and BasicService). When attempting to resolve BasicService, the service provider is not going to look at any of the interfaces the class is implementing and check whether they're already registered. Also, running container.Locate<BasicService>() will give you a new instance each time because you've never explicitly registered BasicService as a singleton.

This behavior is correct and working as intended.

To mimic your assumed behavior you'd have to do something like the following:

container.Configure(c =>
{
   c.ExportAs<BasicService, IBasicService>().Lifestyle.Singleton();
   c.ExportFactory<IBasicService, BasicService>(bs => bs).Lifestyle.Singleton();
});

Okay, thanks.
It works for me this way

[Fact]
        public void Export_Singleton()
        {
            var container = new DependencyInjectionContainer();

            container.Configure(c =>
            {
                c.Export<BasicService>().As<BasicService>().As<IBasicService>().Lifestyle.Singleton();
            });

            var interfaceService = container.Locate<IBasicService>();
            var typeService = container.Locate<BasicService>();

            Assert.IsType<BasicService>(interfaceService);
            Assert.IsType<BasicService>(typeService);
            Assert.Same(interfaceService, typeService);
        }