Making dependency injection optional by introducting a factory?
So I have a piece of software containing a brunch of service classes. Those services ta开发者_Python百科ke some dependencies though their respective constructors.
I have designed with dependency injection in mind, but developers who are going to build on top of the software, may not want to use DI. Therefore I have not implemented an IOC container, so it is up to the developer to introduce one if desired.
My problem is that the software comes with an administration website, which uses these services. I don't want to hardcode the service dependencies in the site, because I want to make it possible for the developers to switch them if they want to.
So how should I go about this?
I was thinking about introducing a factory for services, and give it a fixed static location somewhere. Then use it on the site.
public class ServiceFactory : IServiceFactory
{
public static IServiceFactory Current { get; set; }
static ServiceFactory()
{
Current = new ServiceFactory();
}
public TService Create<TService>()
{
// Creation logic here.
}
}
Developers will be able to control things by setting their own implementation of IServiceFactory
to the static ServiceFactory.Current
property.
Is this the way to go?
Two things I would like to note.
- What you are proposing is not Dependency Injection, rather Service Location. They are not the same.
- Ideally dependency injection is fully transparent to a developer. I.e. the true dependencies enter through the constructor and not via an indirection.
Have you looked into the CommonServiceLocator library? It is designed to provide an abstraction layer over an IOC container, however you could equally use it to abstract a service factory as you describe, that way your application would be able to resolve its dependencies without necessarily knowing whether they were coming from DI or a factory implementation...
精彩评论