NicholasPei

NicholasPei
这篇文章主要介绍如下内容1.Introduction对于DI工作3年以上的开发人员应该都是比较熟悉了。如果你是比较初级的开发人员我建议可以看看资料了解下DI以及相关的概念。推荐阅读如下http://en.wikipedia.org/wiki/Dependency_injectionhttp://en.wikipedia.org/wiki/Abstract_factoryhttp://martinfowler.com/articles/injection.html#UsingAServiceLocator在ASP.NET MVC 3之前的版本是使用Abstract FactoryService Locator来作为DI的容器而在3中你可以使用新的Dependency Resolver来结合Container工具更加简单的实现DI。2. Dependency Resolution什么是Dependency Resolution一个Controller需要一个Repository,那么这个Repository就是Controller的一个依赖项。上面是传统的一个Deoendency的使用例子(代码中)。在ASP.NET MVC 3中提供了Dependency Reolver它给我们提供了一个好的Dependency Resolution。当请求中需要某个组件时Dependency Resolver就会对应的提供一个控件T。3.Benefits使用Dependency Resolution有啥好处呢a.Flexibility让整个系统的架构更加灵活。开发人员可以更加专注于架构而不是功能的实现。b.Testability让整个系统的测试更加容易。测试部分和具体的功能实现依赖项要小很多了。c.Extensibility可扩展性增强。4.IdependencyResolver的使用The DependencyResolver is a member of the System.Web.Mvc NameSpace and its job is quite simple: to provide a central registration point for your chosen IoC Container. Prior to MVC 3, we often dealt with our chosen IoC container directly. In MVC 3, there is an abstraction layer (the DependencyResolver Class) that we will interact with directly. Whether your chosen IoC Container is Windsor, StructureMap or Unity, you can take advantage of this new feature.IdependencyResolver接口有两个方法object GetService(Type serviceType) IEnumerableobject GetServices(Type serviceType)如何使用它呢一般都是让结合一个IoC Container来使用。我这里给出几个例子结合Autofac使用我比较喜欢Autofac但是发现结合IdependencyResolver来使用Autoc相对还是比较复杂的。需要好好研究研究。结合StructureMap:1. public class StructureMapDependencyResolver : IDependencyResolver 2. { 3. IContainer _container; 4. 5. public StructureMapDependencyResolver(IContainer container) 6. { 7. _container container; 8. } 9. 10. 11. public object GetService(Type serviceType) 12. { 13. object instance _container.TryGetInstance(serviceType); 14. 15. if (instance null !serviceType.IsAbstract) 16. { 17. _container.Configure(c c.AddType(serviceType, serviceType)); 18. instance _container.TryGetInstance(serviceType); 19. } 20. 21. return instance; 22. } 23. 24. public IEnumerableobject GetServices(Type serviceType) 25. { 26. return _container.GetAllInstances(serviceType).Castobject(); 27. } 28. }结合Unity1. public class UnityDependencyResolver : IDependencyResolver 2. {