有很多方法可以解决这个问题。您不需要一个框架来执行依赖注入(尽管手动编写它们可能会使您的IoC容器开始变得有意义)。
既然你想在多个实现上调用GetByID,我会先从你有的ProductController中提取一个接口。
public interface IProductController
{
Product GetByID(int id);
}
public class SomeProductController : IProductController
{
public Product GetByID(int id)
{
return << fetch code >>
}
}
从那里,你可以解决多种方式,一些例子实施:
public class ProductFetcher
{
// option 1: constructor injection
private readonly IProductController _productController;
public ProductFetcher(IProductController productController)
{
_productController = productController;
}
public Product FetchProductByID(int id)
{
return _productController.GetByID(id);
}
// option 2: inject it at the method level
public static Product FetchProductByID(IProductController productController, int id)
{
return productController.GetByID(id);
}
// option 3: black box the whole thing, this is more of a servicelocator pattern
public static Product FetchProductsByID(string controllerName, int id)
{
var productController = getProductController(controllerName);
return productController.GetByID(id);
}
private static IProductController getProductController(string controllerName)
{
// hard code them or use configuration data or reflection
// can also make this method non static and abstract to create an abstract factory
switch(controllerName.ToLower())
{
case "someproductcontroller":
return new SomeProductController();
case "anotherproductcontroller":
// etc
default:
throw new NotImplementedException();
}
}
}
这一切都有点取决于谁去负责选择哪些ProductController的实施需要使用。
依赖注入(控制反转)在这种情况下真的很有用。它允许您在运行时更改ProductController的行为,如上所示。 – Jens 2010-11-22 12:48:40
谢谢,我一直在寻找使用某种DI框架。 – Simon 2010-11-22 14:02:44