我遇到这样的问题:
public interface IBaseVMFactory
{
public BaseVm Create(TransientDependency otherVM);
}
public class BaseVM
{
BaseVM(ChildVM1 child1, ChildVM2 child2)
}
public class ChildVM1
{
ChildVM1(TransientDependency otherVM)
}
我的所有viewModels(..VM)都需要是瞬态的。我需要让childVM1获得与工厂相同的otherVM实例。
我尝试将BaseVm注册为ScopedLifestyle,并手动实现工厂并在解析范围内时传递实例。 但是在解析时我仍然得到了另一个VM的新实例。
我错过了一些明显的东西吗?
谢蒂尔。
答案 0 :(得分:0)
我尝试使用以下代码复制您的Windsor 3.2问题:
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>();
}
}
}
令我惊讶的是,这才有效。因此,工厂似乎正在接管其创建环境的范围。我希望这会对你有所帮助。
亲切的问候, Marwijn。