DI容器、单元测试框架、模仿工具
笔记:
1.Ninject条件绑定常用方法:
When(predicate) //当predicate结果为true时,实施绑定。(predicate一个lambda表达式)
WhenclassHas<T>() //当被注入的类以注解属性进行注释,且其类型为T时,实施绑定([T])
WhenInjectedInfo<T>() //当要被注入的类是类型T时,实施绑定
2.使用Ninject:
1.创建依赖解析器(Infrastructure)
using System; using System.Collections.Generic; using System.Web.Mvc; using Essentialtools.Models; using Ninject; namespace Essentialtools.Infrastructure { public class NinjdectDependencyResolver:IDependencyResolver { private IKernel kernel; public NinjdectDependencyResolver() { //创建Ninject内核的实例 kernel = new StandardKernel(); AddBindings(); } public object GetService(Type serviceType) { return kernel.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return kernel.GetAll(serviceType); } //建立接口与实现类之间的关系 private void AddBindings() { //构造器 kernel.Bind<IValueCalculator>().To<LinqValueCalculator>(); //属性 // kernel.Bind<IDiscoutnHelper>().To<DefaultDiscoutnHelper>().WithPropertyValue("DiscountSize",20M); //构造器参数 kernel.Bind<IDiscoutnHelper>().To<DefaultDiscoutnHelper>().WithConstructorArgument("discountParam", 30M); //条件绑定 kernel.Bind<IDiscoutnHelper>().To<FlexibleDiscountHelper>().WhenInjectedInto<LinqValueCalculator>(); } } }
2.注册依赖解析器(Global.asax)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; using Essentialtools.Infrastructure; namespace Essentialtools { // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明, // 请访问 http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); //注册依赖解析器 DependencyResolver.SetResolver(new NinjdectDependencyResolver()); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
3.重构控制器
................. //构造器 private IValueCalculator calc; public HomeController(IValueCalculator calcParam) { calc = calcParam; } .................
单元测试 这个是思维方法和开发风格决定的。
源码:http://yunpan.cn/cQ9QEgtrWXaS9 访问密码 bbd2
时间: 2024-10-25 21:19:20