Using Factory to get Injected objects
Is it good practice to have a Factory method to retrieve injected objects or is it OK to just use the factory method from the DI framework?
I'm using structure map, should I just use ObjectFactory.GetInstance();, or should I create factory class and inside this class call ObjectFactory.GetInstance();? because if I call ObjectFactory.GetInstance(); in my classes I would be creating coupling to the DI 开发者_JAVA百科framework? sorry if I'm being ignorant, I'm new to this concepts. Thanks!
If you are already using a DI framework why re-implement the factory pattern when it is already provided by the framework? Also you shouldn't be creating a dependency with the DI framework in the business layers of the application. There you should be abstracting with interfaces and abstract classes. The DI framework should only be used only at the highest level, for example in the GUI to perform the plumbing of the lower layers and select for instance a suitable data access layer.
A factory method is useful when you need fine-grained control over when you need the instance. Still, you should not depend directly on the container itself but rather inject a factory method as a dependency. Here's an example illustrating 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 would look something like this:
var container = new Container(cfg =>
cfg.For<ISomeService>().Use(() => new SomeServiceImpl())
);
精彩评论