gpt4 book ai didi

configuration - StructureMap HowTo:深对象的条件构造

转载 作者:行者123 更新时间:2023-12-02 04:16:57 27 4
gpt4 key购买 nike

我在有条件地创建依赖项方面遇到困难。谷歌搜索,我还没有找到使用BuildStack和条件谓词的好例子。

这是我在注册表中执行的操作:

//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

这就是我想要的结构映射到具有IFoo正确依赖关系的AutoWire:
//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

我无法弄清楚如何通过 GiveUsProperFoosWhenWeDontAskDirectly测试。

我想在需要 FooA时获取 IDoStuffWithFooA进行初始化,而在 FooB时需要 IDoStuffWithFooB进行初始化,无论何时需要在图中。条件谓词的正确语法是什么?

最佳答案

通常最好尝试避免使用该语法进行条件构造,这比“使用”更难解释。您的情况可以使用以下方法解决:

        For<IDoStuffWithFooA>().Use<DoStuffWithFooA>().Ctor<IFoo>().Is<FooA>();
For<IDoStuffWithFooB>().Use<DoStuffWithFooB>().Ctor<IFoo>().Is<FooB>();

For<IFoo>().Use<FooZ>();

Scan(
s =>
{
s.TheCallingAssembly();
s.WithDefaultConventions();
});

关于configuration - StructureMap HowTo:深对象的条件构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2425565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com