StructureMap - DI - Multiple Concrete Implementation

[亡魂溺海] 提交于 2019-12-12 03:07:03

问题


I have referred multiple threads for solution but those did not help :( Any help to provide solution in terms of code on below problem is appreciated

class Program
{
    static void Main(string[] args)
    {
        //StructureMapConfiguration();

        var registry = new Registry();
        registry.IncludeRegistry<DependencyRegistry>();

        var container = new Container(registry);


        var depend = container.GetInstance<ITest>();
        var controller1 = new Controller1(depend);
        controller1.M1();

        var controller2 = new Controller2(depend);
        controller1.M1();
        Console.Read();
    }

}


public interface ITest
{
    void Method();
}

public class A : ITest
{
    public void Method()
    {
        Console.WriteLine("A");
    }
}

public class B : ITest
{
    public void Method()
    {
        Console.WriteLine("B");
    }
}


public class C : ITest
{
    public void Method()
    {
        Console.WriteLine("C");
    }
}

public interface IController
{
    void M1();
}

public class Controller1 : IController
{
    private ITest _test;
    public Controller1()
    {

    }
    public Controller1(ITest test)
    {
        _test = test;
    }

    public void M1()
    {
        _test.Method();
    }
}

public class Controller2 : IController
{
    private ITest _test;
    public Controller2(ITest test)
    {
        _test = test;
    }

    public void M1()
    {
        _test.Method();
    }
}

public class DependencyRegistry : Registry
{
    public DependencyRegistry()
    {

        For<ITest>().Use<A>().Named("A");
        For<ITest>().Use<B>().Named("B");
        For<ITest>().Use<C>().Named("C");


        For<IController>().Add<Controller1>().Ctor<ITest>().Is(i => i.GetInstance<ITest>("A"));
        For<IController>().Add<Controller2>().Ctor<ITest>().Is(i => i.GetInstance<ITest>("B"));

        Scan(x =>
        {
            x.AssembliesFromApplicationBaseDirectory();
            x.AddAllTypesOf<ITest>().NameBy(type => type.Name);
            x.WithDefaultConventions();
        });

    }
}

}

Actual Result: Everytime I am getting instance of class C for Controller1 and Controller2

Expected Result: For Controller1, I need instance of class A and for Controller2, I need instance of class B

Thanks in advance

来源:https://stackoverflow.com/questions/40842546/structuremap-di-multiple-concrete-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!