Can i use a Factory to implement dependency injection

Someone told me that before dependency injection frameworks came around there developers would use a factory to implement DI. Can anyone provide an example how a factory pattern can be used for DI. I mean just by thinking about it a factory is a depenendency injector but i cant find any examples on the web.


This off the top of my head, untested code (with C#)

public class CarFactory : ICarFactory{

   private static CarFactory instance = null;

   public static ICarFactory SingletonInstance {
       get {
            if (this.instance == null){
                 this.instance = new CarFactory();
                 return this.instance;
            }
       },
       set {
           this.instance = value;
       }
   }

   public ICar CreateCar(string make){

       switch(make)
       {
           case "Toyota": return new Toyota();
           case "Honda" : return new Honda();
           default: throw new Exception();
       }

   }

}

public interface ICarFactory {
    ICar CreateCar(string make);
} 

public class Toyota : ICar
{
}

public class Honda : ICar
{
}

And usage would be something like :

ICar car = CarFactory.SingletonInstance.CreateCar("Toyota");

Exposing the singleton instance of the CarFactory publically enables you to mock the CarFactory for your unit tests and you can have your mocked CarFactory return mocked ICars when calling CreateCar.

Now replace the Cars in the factory by actual dependencies such as classes that implement services. And voila, you have a Factory that contains all your dependencies. You can now use the Factory to "resolve" your dependencies. You can take the example and push it further by using generic types and a dictionary (hashtable) where the key is the type name and the value the implementation instance such as:

public T Create<T>(){
    return mydictionary.get(typeof(T).Name);
}

Something like that... You get the drift...

Hope it helps!

链接地址: http://www.djcxy.com/p/13620.html

上一篇: 使用$ scope。$ emit和$ scope。$ on

下一篇: 我可以使用工厂来实现依赖注入