IOrderStrategy orderInsertStrategy = new OrderSynchronous(); 在Martin Fowler的文章《IoC容器和Dependency Injection模式》中,提出了解决这类问题的办法,他称之为依赖注入。不过由于PetShop并没有使用诸如Sping.Net等IoC容器,因此解决依赖问题,通常是利用配置文件结合反射来完成的。在领域对象Order类中,是这样实现的:
public class Order { private static readonly IOrderStategy orderInsertStrategy = LoadInsertStrategy(); private static IOrderStrategy LoadInsertStrategy() { // Look up which strategy to use from config file string path = ConfigurationManager.AppSettings["OrderStrategyAssembly"]; string className = ConfigurationManager.AppSettings["OrderStrategyClass"];
// Load the appropriate assembly and class return (IOrderStrategy)Assembly.Load(path).CreateInstance(className); } } 在配置文件web.config中,配置如下的Section: