0

「ITestProperty」を実装するオブジェクト「TestProperty」があります。"TestProperty" は、文字列コンストラクター引数を取ります。これは、CtorDependency または WithCtorArg の行に沿って何かを使用して StructureMap で構成されます。

「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 に答える