0

我有一个实现“ITestProperty”的对象“TestProperty”。“TestProperty”采用字符串构造函数参数。这是在 StructureMap 中使用类似于 CorDependency 或 WithCtorArg 的东西配置的。

我想将“ITestProperty”的一个实例(用“TestProperty”实现)作为属性注入另一个类。当我尝试运行代码时出现异常(StructureMap 错误代码 205,“缺少请求的实例属性”)。

这是重现问题的简化版本:

测试:

[Test]
public void Can_resolve_the_correct_property()
{
    ObjectFactory.Initialize( x => x.AddRegistry( new TestRegistry() ) );

    var instance = ObjectFactory.GetInstance<TestController>();
}

注册表设置:

public class TestRegistry : Registry
{
    public TestRegistry()
    {
        ForRequestedType<ITestProperty>().AddInstances( 
            i => i.OfConcreteType<TestProperty>().WithName( "Test" )
                .CtorDependency<string>( "arg" ).Is( "abc" )
        );

        //ForConcreteType<TestProperty>().Configure
            .CtorDependency<string>( "arg" ).Is( "abc" );

        ForConcreteType<TestController>().Configure
            .SetterDependency( p => p.Property ).Is<TestProperty>()
            .WithName( "Test" );
    }
}

测试对象:

public interface ITestProperty { }

public class TestProperty : ITestProperty
{
    private readonly string arg;

    public TestProperty( string arg )
    {
        this.arg = arg;
    }

    public string Arg { get { return arg; } }
}

public class TestController
{
    public ITestProperty Property { get; set; }
}

当我们去初始化上面的“TestController”对象时,就会抛出异常。可以用 StructureMap 做到这一点吗?假设这是可能的,我需要做什么才能让它工作?

提前致谢。

4

1 回答 1

1

有几种方法可以做到这一点,正如 Josh 所提到的,如果命名实例很重要,那么您希望在注册表中使用它:

ForRequestedType<ITestProperty>().AddInstances(i => 
    i.OfConcreteType<TestProperty>().WithName("Test")
        .WithCtorArg("arg").EqualTo("abc"));

ForConcreteType<TestController>().Configure
    .SetterDependency(p => p.Property).Is(c => c
        .GetInstance<ITestProperty>("Test"));

否则,您可以这样做:

ForRequestedType<ITestProperty>().TheDefault.Is
    .OfConcreteType<TestProperty>()
    .WithCtorArg("arg").EqualTo("abc");

ForConcreteType<TestController>().Configure
    .SetterDependency(p => p.Property).IsTheDefault();

此外,这是旧的 StructureMap 语法,您可能需要更新到最新版本。这是新的语法:

For<ITestProperty>().Add<TestProperty>().Named("Test")
    .Ctor<string>("arg").Is("abc");

ForConcreteType<TestController>().Configure
    .Setter(p => p.Property).Is(c => c
        .GetInstance<ITestProperty>("Test"));
于 2010-09-23T18:57:31.057 回答