什么是加载/选择“控制器”类的最佳方式
问题描述:
我不确定我是否使用了正确的术语,但我有几个Controller类在ASP.NET Web应用程序中返回使用不同数据源的对象。即什么是加载/选择“控制器”类的最佳方式
Product p = ProductController.GetByID(string id);
我想要做的就是使用一个控制器工厂,可以从不同的ProductController中选择。我了解基本的工厂模式,但是想知道是否有一种方法只用一个字符串加载选定的cotroller类。
我想实现的是返回新的/不同的控制器而不必更新工厂类的方法。有人建议我看看依赖注入和MEF。我看了一下MEF,但我一直无法弄清楚如何在Web应用程序中实现这一点。
我很想得到正确方向上的一些指示。
答
有很多方法可以解决这个问题。您不需要一个框架来执行依赖注入(尽管手动编写它们可能会使您的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