Using Factory to Get Injected Objects

Is it good to use the Factory method to retrieve injectable objects, or is it okay to just use the Factory method from within the DI framework?

I am using a structural map, should I just use ObjectFactory.GetInstance (); or should I create a Factory class and call ObjectFactory.GetInstance (); inside this class? because if I call ObjectFactory.GetInstance (); in my classes would I create a link to a DI map? sorry if I am clueless, I am new to this concept. Thanks!

+6
c # dependency-injection structuremap
source share
2 answers

If you are already using the DI framework, why reuse the factory pattern if one is already provided by the framework? Also, you should not create a dependency with a DI framework in the business layers of the application. There you should abstract away with interfaces and abstract classes. The DI frame should be used only at the highest level, for example, in the graphical interface for plumbing the lower layers, and choose, for example, the appropriate level of data access.

+3
source share

A factory method is useful when you need fine-grained control, when you need an instance. However, you should not directly depend on the container itself, but rather introduce the factory method as a dependency. Here is an example to illustrate this:

public class SomeController { private Func<ISomeService> _serviceFactory; public SomeController(Func<ISomeService> serviceFactory) { _serviceFactory = serviceFactory; } public void DoSomeWork() { var service = _serviceFactory(); .... } } 

The StructureMap registration code will look something like this:

 var container = new Container(cfg => cfg.For<ISomeService>().Use(() => new SomeServiceImpl()) ); 
+3
source share

All Articles