Search code examples
c#dependency-injectionautofacfactorydependency-inversion

Dependency Inversion with a List<T> in a method


How would one implement Dependency Inversion on a given class like the following code? Problem is the function "Add" in class A, which containts the new Keyword.

I'm using Autofac for Dependency Injection.

Should I create an "IBFactory" which I register in my Autofac, or use Method Injection, or something completely else?

public class A {
   List<B> _list = new List<B>();
   ILogger _logger;

   public A(ILogger logger) {  //Depency Injection using Autofac
        _logger = logger;
   }

   public Add(object X) {
        if (X is String)
           _list.Add(new B1());
        else
           _list.Add(new B2());
   }

}

public interface B {
}

public class B1 : B {
}

public class B2 : B {
}

Solution

  • A factory delegate could be used at act as a factory for the desired types

    public class A {
        List<B> _list = new List<B>();
        private readonly ILogger logger;
        private readonly Func<B1> factory1;
        private readonly Func<B2> factory2;
    
        public A(ILogger logger, Func<B1> factory1, Func<B2> factory2) {  
            //Depency Injection using Autofac
            this.logger = logger;
            this.factory1 = factory1;
            this.factory2 = factory2;
       }
    
       public Add(object X) {
            if (X is String)
               _list.Add(factory1());
            else
               _list.Add(factory2());
       }
    }
    

    If type T is registered with the container, Autofac will automatically resolve dependencies on Func<T> as factories that create T instances through the container.

    Reference Autofac: Delegate Factories