StructureMap构造函数的参数应用于属性。

4
我正在使用StructureMap注册一个类,该类的构造函数参数包括一个TimeSpan,另一个TimeSpan是该类的属性。当我在StructureMap中使用命名构造函数参数时,构造函数参数的值会应用于我的构造函数参数和任何公共类属性,这些属性都是TimeSpans。我还尝试将类切换为DateTimes而不是TimeSpans,并获得了相同的结果。因此,我的问题是,我是否正确地使用了StructureMap,或者应该以另一种方式注册这个类?谢谢!
以下是一个简单的接口和类,用于演示这个问题:
public interface ITimeSpanTest
{
  TimeSpan Timeout { get; set; }
  TimeSpan LogTimeout { get; set; }
}

public class TimeSpanTest : ITimeSpanTest
{
  public TimeSpan LogTimeout { get; set; }
  public TimeSpan Timeout { get; set; }

  public string Process { get; set; }

  public TimeSpanTest(TimeSpan logTimeout, string process)
  {
    this.Timeout = TimeSpan.FromSeconds(1);
    this.LogTimeout = logTimeout;
    this.Process = process;
  }
}

以下是StructureMap的注册代码

Container container = new Container();

container.Configure(c =>
{
  c.Scan(x =>
  {
    x.TheCallingAssembly();
  });

  c.For<ITimeSpanTest>().Use<TimeSpanTest>()
    .Ctor<TimeSpan>("logTimeout").Is(TimeSpan.FromMinutes(5))
    .Ctor<string>("process").Is("Process")
    .Singleton();
});

这是StructureMap容器的container.Model.For().Default.DescribeBuildPlan()函数的输出结果。
PluginType: SMTest.ITimeSpanTest
Lifecycle: Singleton
new TimeSpanTest(TimeSpan, String process)
  ? TimeSpan = Value: 00:05:00
  ? String process = Value: Process
Set TimeSpan LogTimeout = Value: 00:05:00
Set TimeSpan Timeout = Value: 00:05:00

您可以看到,TimeSpan构造函数参数的"logTimeout"名称似乎被忽略了。Timeout属性被设置为00:05:00,而应该是00:00:01。我正在使用StructureMap 3.1.6.186。


你使用StructureMap的目标是什么?如果不知道你想要做什么,很难说你的使用是否正确。 - jclozano
1个回答

2

我在这里没有得到答案,但我已经发布到了StructureMap Google Group。Jeremy Miller的回答在这里

基本上,这是一个已知问题,可能不会修复,因为可以通过使Timeout只读来轻松解决。这可以通过在Timeout属性中删除set来完成。例如:

public interface ITimeSpanTest
{
  TimeSpan Timeout { get; }
  TimeSpan LogTimeout { get; set; }
}

public class TimeSpanTest : ITimeSpanTest
{
  public TimeSpan LogTimeout { get; set; }
  public TimeSpan Timeout { get; }

  public string Process { get; set; }

  public TimeSpanTest(TimeSpan logTimeout, string process)
  {
    this.Timeout = TimeSpan.FromSeconds(1);
    this.LogTimeout = logTimeout;
    this.Process = process;
  }
}

在这个特定的情况下,这样做是有效的。但是,问题似乎在于StructureMap setter注入器将logTimeout设置应用于所有公共TimeSpan属性。我还测试了DateTime,它表现出相同的行为。但是,float和int类型则不会出现这种情况。这发生在StructureMap 3的最后几个版本和最新版的StructureMap 4中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接