开发者

How to StructureMap configuration?

On AppEngine "Franch" and "English" as a dependency injection what do I do?

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>(); 

          开发者_StackOverflow社区      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";
    }
}


As the contract for FrenchGreeter and EnglishGreeter is the same, StructureMap will not know which to use. For each wireing it uses only one instance per contract. Try something like this:

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"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜