我找不到任何使用 scopeRootBinder 的示例。我不确定它是否可以帮助我。这是问题(测试)。我需要使用自己的 Component2 实例构建 ChildService 的每个实例。
[TestMethod]
public void CastleContainer_ChildServices_GetItsOwnObject()
{
var container = new WindsorContainer();
container.Register(Component.For<IRootService>().ImplementedBy<RootService>().LifestyleTransient()
.DependsOn(ServiceOverride.ForKey("childServices")
.Eq("ChildService", "ChildService")));
container.Register(Component.For<IChildService>().ImplementedBy<ChildService>().LifestyleTransient().Named("ChildService"));
//nearest in 3.2 container.Register(Component.For<Component2>().ImplementedBy<Component2>().LifestyleBoundToNearest<IChildService>());
//creates single instance of Component2 container.Register(Component.For<Component2>().ImplementedBy<Component2>().LifestyleBoundTo<ChildService>());
Func<IHandler[], IHandler> scopeRootBinder = ScopeRootBinder;
container.Register(Component.For<Component2>().ImplementedBy<Component2>().LifestyleBoundTo(scopeRootBinder));
container.Register(Component.For<Component3>().ImplementedBy<Component3>().LifestyleTransient());
var rs = container.Resolve<IRootService>();
var first = rs.ChildServices[0];
var second = rs.ChildServices[1];
ReferenceEquals(first, second).Should().BeFalse();
ReferenceEquals(first.Component2, second.Component2).Should().BeFalse("each child service should have its own Component2");
ReferenceEquals(first.Component2, first.Component3.Component2).Should().BeTrue();
ReferenceEquals(second.Component2, second.Component3.Component2).Should().BeTrue();
}
private IHandler ScopeRootBinder(IHandler[] handlers)
{
//not clear what should be here???
var r = handlers.FirstOrDefault(h => h.ComponentModel.Services.Any(t => t.Name == "IChildService"));
return r;
}
这是课程
public interface IRootService
{
IChildService[] ChildServices { get; }
}
public class RootService : IRootService
{
public RootService(IChildService[] childServices)
{
ChildServices = childServices;
}
public IChildService[] ChildServices { get; private set; }
}
public interface IChildService
{
Component3 Component3 { get; }
Component2 Component2 { get; }
}
public class ChildService: IChildService
{
public ChildService(Component2 comp, Component3 comp3)
{
Component2 = comp;
Component3 = comp3;
}
public Component3 Component3 { get; set; }
public Component2 Component2 { get; set; }
}
public class Component3
{
public Component3(Component2 comp)
{
Component2 = comp;
}
public Component2 Component2 { get; set; }
}
public class Component2
{
private Guid _guid = Guid.NewGuid();
}