如何构造地图配置?

时间:2011-09-01 05:43:32

标签: c# inversion-of-control structuremap

在App Engine上“法语”和“英语”作为依赖注入我该怎么办?

class Program
{
    static void Main(string[] args)
    {
        IContainer container = ConfigureDependencies();

        IAppEngine appEngine = container.GetInstance<IAppEngine>();

        IGeeter g1 = container.GetInstance<IGeeter>("Franch");
        IGeeter g2 = container.GetInstance<IGeeter>("English");

        appEngine.Run();



    }

    private static IContainer ConfigureDependencies()
    {


        return new Container(x =>
            {                    
                x.For<IGeeter>().Add<FrenchGreeter>().Named("Franch");
                x.For<IGeeter>().Add<EnglishGreeter>().Named("English"); 

                x.For<IAppEngine>().Use<AppEngine>(); 

                x.For<IGeeter>().Use<EnglishGreeter>();
                x.For<IOutputDisplay>().Use<ConsoleOutputDisplay>();

            });
    }

}

public interface IAppEngine
{
    void Run();
}

public interface IGeeter
{
    string GetGreeting();
}
public interface IOutputDisplay
{
    void Show(string message);
}

public class AppEngine : IAppEngine
{
    private readonly IGeeter english;
    private readonly IGeeter franch;
    private readonly IOutputDisplay outputDisplay;

    public AppEngine(IGeeter english,IGeeter franch, IOutputDisplay outputDisplay)
    {
        this.english = english;
        this.franch = franch;
        this.outputDisplay = outputDisplay;

    }

    public void Run()
    {
        outputDisplay.Show(greeter.GetGreeting());
    }
}

public class EnglishGreeter : IGeeter
{
    public string GetGreeting()
    {
        return "Hello";
    }
}

public class FrenchGreeter : IGeeter
{
    public string GetGreeting()
    {
        return "Bonjour";
    }
}

1 个答案:

答案 0 :(得分:3)

由于FrenchGreeter和EnglishGreeter的合约相同,StructureMap不知道使用哪个。对于每个连线,它每个合约只使用一个实例。尝试这样的事情:

For<IGreeter>().Use<FrenchGreeter>().Named("French");
For<IGreeter>().Use<EnglishGreeter>().Named("English");
For<IAppEngine>().Use<AppEngine>()
  .Ctor<IGreeter>("French").Is(x => x.TheInstanceNamed("French"))
  .Ctor<IGreeter>("English").Is(x => x.TheInstanceNamed("English"));