【问题标题】:Autofac - One interface, multiple implementationsAutofac - 一个接口,多种实现
【发布时间】:2019-08-09 06:00:12
【问题描述】:

单界面:IDoSomething {...}

两个类实现该接口:

ClassA : IDoSomething {...}

ClassB : IDoSomething {...}

一个类使用这些类中的任何一个。

public class DummyClass(IDoSomething doSomething) {...}

没有 Autofac 的代码:

{
....
IDoSomething myProperty;

if (type == "A")

    myProperty = new DummyClass (new ClassA());

else

    myProperty = new DummyClass (new ClassB());


myProperty.CallSomeMethod();
....
}

是否可以使用 Autofac 实现类似的功能?

提前致谢,

【问题讨论】:

标签: autofac


【解决方案1】:

我记得,您正在寻找的是Strategy Pattern。您可能有单个接口的 N 个实现。只要您将它们全部注册,Autofac 或任何其他 DI 框架都应该提供它们。

其中一个选项是使用私有 setter 或仅在 Interface 内部的 getter 创建属性声明,然后在每个类中实现该属性。在需要选择正确实现的类中,构造函数应该有参数IEnumerable<ICommon>

Autofac 或任何其他 DI 框架应该注入所有可能的实现。之后,您可以旋转foreach 并搜索所需的属性。

它可能看起来像这样。

public interface ICommon{ 
        string Identifier{get;}
        void commonAction();
    }

    public class A: ICommon{
        public string Identifier { get{return "ClassA";}  }

        public void commonAction()
        {
            Console.WriteLine("ClassA");
        }
    }

    public class A: ICommon{
        public string Identifier { get{return "ClassB";}  }

        public void commonAction()
        {
            Console.WriteLine("ClassA");
        }
    }

    public class Action{
        private IEnumerable<ICommon> _common;

        public Action(IEnumerable<ICommon> common){
            _common = common;
        }

        public void SelectorMethod(){
            foreach(var classes in _common){
                if(classes.Identifier == "ClassA"){
                    classes.commonAction();
                }
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-03
    • 2020-08-10
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多