gpt4 book ai didi

StructureMap 异常代码 205 缺少请求的实例属性

转载 作者:行者123 更新时间:2023-12-04 10:45:33 32 4
gpt4 key购买 nike

我正在尝试最新版本的 StructureMap,以了解 IoC 容器等。作为我的第一次测试,我有以下类(class):

public class Hospital
{
private Person Person { get; set; }
private int Level { get; set; }

public Hospital(Person employee, int level)
{
Person = employee;
Level = level;
}

public void ShowId()
{
Console.WriteLine(this.Level);
this.Person.Identify();
}
}

然后我像这样使用 StructureMap:
static void Main()
{
ObjectFactory.Configure(x =>
{
x.For<Person>().Use<Doctor>();
x.ForConcreteType<Hospital>().Configure.Ctor<int>().Equals(23);
});

var h = ObjectFactory.GetInstance<Hospital>();

h.ShowId();
}

所以我将一个 Doctor 对象作为第一个构造函数参数传递给 Hospital,并且我试图设置 level参数为 23。当我运行上面的代码时,我得到:

Unhandled Exception: StructureMap.StructureMapException: StructureMap Exception Code: 205 Missing requested Instance property "level" for InstanceKey "5f8c4b74-a398-43f7- 91d5-cfefcdf120cf"



所以看起来我没有设置 level参数。有人可以指出我正确的方向 - 我如何设置 level构造函数中的参数?

干杯。
贾斯。

最佳答案

你非常接近。您不小心在依赖项表达式上使用了 System.Object.Equals 方法,而不是 Is 方法。我还建议在配置字符串或值类型(int、DateTime)等常见类型时指定构造函数参数名称以避免歧义。

这是我对您正在寻找的内容的测试:

    [TestFixture]
public class configuring_concrete_types
{
[Test]
public void should_set_the_configured_ctor_value_type()
{
const int level = 23;
var container = new Container(x =>
{
x.For<Person>().Use<Doctor>();
x.ForConcreteType<Hospital>().Configure.Ctor<int>("level").Is(level);
});

var hospital = container.GetInstance<Hospital>();

hospital.Level.ShouldEqual(level);
}
}

关于StructureMap 异常代码 205 缺少请求的实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2248564/

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