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 {
}
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 onFunc<T>
as factories that createT
instances through the container.