我很难有条件地造成依赖。 我尚未找到一个利用建筑标准和条件指数的良好范例。
这里我是在书记官处做的:
//snip
public SomeRegistry()
{
this.InstanceOf<IFoo>().Is.Conditional(
c =>
{
c.TheDefault.Is.ConstructedBy(() => new FooZ());
c.If(
p => p.ParentType.IsAssignableFrom(typeof(IBar)) &&
p.BuildStack.Current.RequestedType.IsAssignableFrom(typeof(IDoStuffWithFooA)))
.ThenIt.Is.ConstructedBy(() => new FooA());
c.If(
p => p.ParentType.IsAssignableFrom(typeof(IBar)) &&
p.BuildStack.Current.RequestedType.IsAssignableFrom(typeof(IDoStuffWithFooB)))
.ThenIt.Is.ConstructedBy(() => new FooB());
});
this.Scan(
s =>
{
s.TheCallingAssembly();
s.WithDefaultConventions();
});
}
//snip
这里的单位测试显示我期望的是什么
//snip
[TestFixture]
public class ConditionalCreationTest
{
[Test]
public void GiveUsFooAWhenDoingStuffWithA()
{
var dependA = ObjectFactory.GetInstance<IDoStuffWithFooA>();
Assert.IsInstanceOfType<FooA>(dependA.Foo);
}
[Test]
public void GiveUsFooBWhenDoingStuffWithB()
{
var dependB = ObjectFactory.GetInstance<IDoStuffWithFooB>();
Assert.IsInstanceOfType<FooB>(dependB.Foo);
}
[Test]
public void GiveUsFooZByDefault()
{
var foo = ObjectFactory.GetInstance<IFoo>();
Assert.IsInstanceOfType<FooZ>(foo);
}
[Test]
public void GiveUsProperFoosWhenWeDontAskDirectly()
{
var bar = ObjectFactory.GetInstance<IBar>();
Assert.IsInstanceOfType<FooA>(bar.DoStuffA.Foo);
Assert.IsInstanceOfType<FooB>(bar.DoStuffB.Foo);
}
[SetUp]
public void SetUp()
{
ObjectFactory.Initialize(a => a.AddRegistry<SomeRegistry>());
}
}
//snip
这是我想要的“结构”到“自治”,而“红十字与红新月”的正确依赖是:
//snip
public class Bar : IBar
{
private IDoStuffWithFooA doStuffA;
private IDoStuffWithFooB doStuffB;
public Bar(IDoStuffWithFooA doStuffA, IDoStuffWithFooB doStuffB)
{
this.doStuffA = doStuffA;
this.doStuffB = doStuffB;
}
public IDoStuffWithFooA DoStuffA
{
get
{
return this.doStuffA;
}
}
public IDoStuffWithFooB DoStuffB
{
get
{
return this.doStuffB;
}
}
}
//snip
我无法说明如何获得<代码>。 GiveUsProperFoosWhen WeDontAskDirectly 考试通过。
我想到FooA
,以便在我需要、>IDoStuffWithFooB
时,无论在图表中需要什么时间,先入门。