如何在StructureMap中通过ExplicitArguments类型选择构造函数?

时间:2018-05-29 07:45:51

标签: c# structuremap

我有一个带有3个构造函数的类Foo,其中每个构造函数都有2个参数。

public class Foo
{
    public string Location;

    public Foo(IContainer container, DefaultData data)
    {
        Location = "DefaultData";
    }

    public Foo(IContainer container, DbData data)
    {
        Location = "DbData";
    }

    public Foo(IContainer container, NetworkData data)
    {
        Location = "NetworkData";
    }
}

public class DefaultData
{
}

public class DbData
{
}

public class NetworkData
{
}

现在,如果我想获得一个实例

var container = new Container();

ExplicitArguments args = new ExplicitArguments();
args.Set(new NetworkData(new decimal(1.3D), 'f'));

var instance = container.GetInstance<Foo>(args);

我总是得到以下例外:

Unable to create a build plan for concrete type TestConsole.DefaultData
new DefaultData(String s, Int32 i)
  ┣ String s = Required primitive dependency is not explicitly defined
  ┗ Int32 i = Required primitive dependency is not explicitly defined
1.) Attempting to create a BuildPlan for Instance of TestConsole.DefaultData -- TestConsole.DefaultData
2.) new Foo(*Default of IContainer*, *Default of DefaultData*)
3.) TestConsole.Foo
4.) Instance of TestConsole.Foo
5.) Container.GetInstance<TestConsole.Foo>({TestConsole.NetworkData=TestConsole.NetworkData})

我也尝试使用自定义IConstructor选择器来解决我的问题,但我没有收到提供的参数(类型),也无法决定我应该使用哪个构造函数。

我想实现传递的ExplicitArguments自动选择构造函数。

0 个答案:

没有答案