Can the WindsorContainer pass a object through the resolve tree when using a factory

332 Views Asked by At

I have a problem like this:

public interface IBaseVMFactory
{
  public BaseVm Create(TransientDependency otherVM);
}

public class BaseVM
{
   BaseVM(ChildVM1 child1, ChildVM2 child2)
}

public class ChildVM1
{
   ChildVM1(TransientDependency otherVM)
}

All my viewModels (..VM) needs to be transient. And I need for the childVM1 to get the same instance of otherVM as given to the factory.

I tried to register the BaseVm as ScopedLifestyle, and manually implementing the factory and passing the instance when resolving inside the scope. But still I get a new instance of the otherVM when resolving.

Am I missing something obvious here?

Kjetil.

1

There are 1 best solutions below

1
On

I tried reproducing your problem with Windsor 3.2 with the code below:

using System.Diagnostics;
using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace ConsoleApplication2
{
    public class SomeViewModel
    {
        public SomeViewModel(ISomeFactory factory)
        {
            var dependency1 = factory.CreateSomeDependency();
            var dependency2 = factory.CreateSomeDependency();

            Debug.Assert(dependency1 != dependency2);
            Debug.Assert(dependency1.Dep == dependency2.Dep);
        }
    }

    public class SomeDependency
    {
        private readonly DepDep _dep;

        public SomeDependency(DepDep dep)
        {
            _dep = dep;
        }

        public DepDep Dep
        {
            get { return _dep; }
        }
    }

    public class DepDep
    {
    }

    public interface ISomeFactory
    {
        SomeDependency CreateSomeDependency();
    }

    class Program
    {
        static void Main(string[] args)
        {
            var container = new WindsorContainer();
            container.AddFacility<TypedFactoryFacility>();
            container.Register(
                Component.For<SomeViewModel>().LifestyleTransient(),
                Component.For<SomeDependency>().LifestyleTransient(),
                Component.For<DepDep>().LifestyleBoundTo<SomeViewModel>(),
                Component.For<ISomeFactory>().AsFactory().LifestyleTransient()
                );
            container.Resolve<SomeViewModel>();
        }
    }
}

To my suprise this just works. So it seems that the factory is now taking over the scope of the context in which it is created. I hope this will help you.

Kind regards, Marwijn.