Search code examples
autofac

Autofac - One interface, multiple implementations


Single interface: IDoSomething {...}

Two classes implement that interface:

ClassA : IDoSomething {...}

ClassB : IDoSomething {...}

One class uses any of those classes.

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

code without Autofac:

{
....
IDoSomething myProperty;

if (type == "A")

    myProperty = new DummyClass (new ClassA());

else

    myProperty = new DummyClass (new ClassB());


myProperty.CallSomeMethod();
....
}

Is it possible to implement something like that using Autofac?

Thanks in advance,


Solution

  • What you are looking for is, as I remember, the Strategy Pattern. You may have N implementations of a single interface. As long you register them all, Autofac or any other DI framework should provide them all.

    One of the options would be to create a declaration of the property with private setter or only getter inside Interface then implement that property in each of the class. In the class where you need to select the correct implementation, the constructor should have the parameter IEnumerable<ICommon>.

    Autofac or any other DI frameworks should inject all possible implementation. After that, you could spin foreach and search for the desired property.

    It may look something like this.

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