为了说明问题,这是我的设置的简化版本。我有一个像这样的工厂:
public interface IFactory{ }
public class Factory : IFactory
{
public Factory()
{
Console.WriteLine("parameterless");
}
//public Factory(int i)
//{
// Console.WriteLine("with parameter : {0}", i);
//}
}
测试这个的程序是一个consoleApp。足以证明我的观点。
static void Main(string[] args)
{
Init();
var factory1 = ObjectFactory.GetInstance<IFactory>();
var factory2 = ObjectFactory.GetInstance<IFactory>();
var factory3 = ObjectFactory.GetInstance<IFactory>();
Console.Read();
}
我在我的 Init 静态方法中设置了 strucutreMap。
public static void Init()
{
ObjectFactory.Initialize(x =>
{
//insert Initialization code here.
});
}
如果我只有一个构造函数并像这样设置 StructureMap :
x.For<IFactory>().Use<Factory>();
效果很好,输出显示无
参数无
参数无
参数
每个调用都会构建一个新实例。
现在,如果我取消注释第二个构造函数,但我想使用无参数的构造函数,并且具有相同的默认生活方式。我该怎么办?
我试过了:
x.SelectConstructor<IFactory>(() => new Factory());
x.For<IFactory>().Use<Factory>();
它只是不起作用:InstanceKey 缺少请求的实例属性“i”
如果我喜欢这样:
x.For<IFactory>().Use(new Factory());
It works, but the output is just one "parameterless" meaning it's not building a new instance for each call. It's using this specific instance I pass in.
The only way I found is to add the [DefaultConstructor] on top of my parameterless constructor and use the standard x.For().Use(); But I don't want to add this attribute and spread the configuration accross my model.
Help?