Dawood Awan
Dawood Awan

Reputation: 7328

Changing constructor parameter value structure map configuration

I have a scenario similar to this:

public class A
{
    private readonly string _test;

    public A() : this("hello world")
    {

    }

    public A(string test)
    {
        _test = test;
    }
}

public class B
{
    private readonly A _a;

    public B(A a)
    {
        _a = a;
    }
}

Now let's say that I have another class, in this class I am going to inject B but instead this time I want to pass a value for _test in class A

public class MainClass
{
    private readonly B _b;

    public MainClass()
    {
        // this is what I want as an injected result by structure map
        _b = new B(new A("change me"));   
    }
}

so to do this in StructureMap, I have created the following Configuration

var testContainer = new Container(cg =>
            {
                cg.For<A>().Use<A>();

                cg.For<B>().Use<B>().Ctor<A>("a").Is<A>().Ctor<string>("test").Is("change me");

            });

            var tsa = testContainer.GetInstance<A>();
            var tsb = testContainer.GetInstance<B>();

But this doesn't seem to inject the string "change me" to the class A

enter image description here

How can I pass the string to Class A constructor for Class B only?

Upvotes: 1

Views: 459

Answers (1)

Evk
Evk

Reputation: 101453

Your current approach defines two separate constructor parameters to construct type B: one of type A and name "a", and another with type string and name "test". Second one is not present and so is ignored.

Instead, you can do it like this:

cg.For<B>().Use<B>().Ctor<A>().IsSpecial(i => i.Type<A>().Ctor<string>().Is("change me"));

Upvotes: 2

Related Questions