castleproject/Windsor

Dispose is called twice when using UsingFactoryMethod with LifestyleTransient

Crabzmatic opened this issue · 0 comments

Windsor 5.1.1

Here is a short reproducer for this problem I'm encountering. MyComponent.Dispose() is called twice. It shouldn't be called twice, it should be called once. When not specifying MyService lifestyle, MyComponent.Dispose() is called only once, as expected.

using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace WindsorOnDestroyReproducer
{
    class MyComponent : IDisposable
    {
        public void Dispose()
        {
            Console.WriteLine("Dispose my component " + GetHashCode());
        }
    }

    class MyComponentFactory
    {
        public MyComponent Create()
        {
            return new MyComponent();
        }
    }

    class MyService
    {
        private readonly MyComponent _myComponent;

        public MyService(MyComponent myComponent)
        {
            _myComponent = myComponent;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using var container = new WindsorContainer();

            container.Register(
                Component.For<MyComponentFactory>().LifestyleSingleton(),

                Component.For<MyComponent>().UsingFactoryMethod(
                    kernel =>
                    {
                        var factory = kernel.Resolve<MyComponentFactory>();
                        var myComponent = factory.Create();
                        return myComponent;
                    }
                ).LifestyleTransient(),

                Component.For<MyService>().LifestyleTransient()
            );

            var service = container.Resolve<MyService>();
        }
    }
}