多重构造与Structuremap变化范围? [英] Multiple constructor with Structuremap changing the scope?

查看:108
本文介绍了多重构造与Structuremap变化范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要说明这个问题,下面是我设置的简化版本。 我有这样一个工厂:

To illustrate the problem, here is a simplified version of my setup. I have a factory like this one :

public interface IFactory{ }

public class Factory : IFactory
{
    public Factory()
    {
        Console.WriteLine("parameterless");
    }

    //public Factory(int i)
    //{
    //    Console.WriteLine("with parameter : {0}", i);
    //}

}

的程序来测试,这是一个consoleApp。足以证明我的观点。

the program to test this is a consoleApp. Enough to prove my point.

static void Main(string[] args)
{
     Init();
     var factory1 = ObjectFactory.GetInstance<IFactory>();
     var factory2 = ObjectFactory.GetInstance<IFactory>();
     var factory3 = ObjectFactory.GetInstance<IFactory>();
     Console.Read();
 }

在我的初始化静态方法我设置strucutreMap。

I setup strucutreMap in my Init static method.

  public static void Init()
        {
            ObjectFactory.Initialize(x =>
            {
                 //insert Initialization code here.
            });
        }

如果我只有一个构造函数和设置StructureMap是这样的:

If I have only one constructor and setup StructureMap like this :

x.For<IFactory>().Use<Factory>();

这完美的作品,并输出显示


that works perfect, and the output shows
parameterless
parameterless
parameterless

每个呼叫建立一个新的实例。

Each call builds a new instance.

现在,如果我去掉了第二个构造函数,但我想用无参数之一,并以同样的默认生活方式。我将如何做呢?

Now if I uncomment the second constructor, but I want to use the parameterless one, and with the same default lifestyle. How would I do?

我试过了:

x.SelectConstructor<IFactory>(() => new Factory());
x.For<IFactory>().Use<Factory>();

这是行不通的:缺少所需的实例属性的i为InstanceKey

It just doesn't work : Missing requested Instance property "i" for InstanceKey

如果我这样做:

 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.

我发现的唯一的办法就是添加[DefaultConstructor]我的参数的构造函数的顶部,并使用标准的x.For()使用()。 但我不希望添加这个属性和s $ P $垫配置翻过我的模型。

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.

帮助?

推荐答案

SelectConstructor采取的具体类型,而不是接口。当然,接口可是没有任何构造函数。 但没有断裂,只是忽略了....所以我不能发现这个错误。

SelectConstructor takes the concrete type, not the interface. Of course, an interface doesnt have any constructor. But nothing breaks, it's just ignored.... so I couldnt spot that error.

 x.SelectConstructor<IFactory>(() => new Factory());
 x.For<IFactory>().Use<Factory>();

 x.SelectConstructor<**Factory**>(() => new Factory());
 x.For<IFactory>().Use<Factory>();

这篇关于多重构造与Structuremap变化范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆