Can i somehow use DI with client of Abscract Factory pattern c#

by MrTKer   Last Updated April 24, 2018 21:05 PM

Let's say i have something like this:

switch(i)  
{  
       case 1: new Class1();break;  
       case 2: new Class2();break;
}

So what's the best practices of doing this if in class where i placed it actively uses DI constructor injection. Does it reasonoble to inject all Class1 and Class2 if it ends up with only one implementation? Thanks



Answers 1


You could inject the container.

switch(i)  
{  
       case 1: myContainer.Resolve<Class1>();break;  
       case 2: myContainer.Resolve<Class2>();break;
}

But a factory is already an abstraction of the new keyword, just like the IoC container is. Instead of using a container to create your objects, you're using a factory.

If you're still not convinced, think of your IoC container as just a super-sized version of a factory. You would still use the IoC container if your object graph is large (i.e. more than one level deep).

But if you're just choosing between one class and another, using the new keyword within a factory method is perfectly adequate.

Robert Harvey
Robert Harvey
April 24, 2018 21:01 PM

Related Questions




C#. Pattern for dynamic report creation

Updated March 05, 2018 14:05 PM


S.O.L.I.D. principles

Updated February 01, 2018 14:05 PM