首页 > 代码库 > Pro ASP.NET MVC 4, 4th edition Reading note---Part(1) DI

Pro ASP.NET MVC 4, 4th edition Reading note---Part(1) DI

 

What I learned from Pro ASP.NET MVC 4 book

Open source of Asp.net MVC

http://www.opensource.org/licenses/ms-pl.html

1. Introduce new trends of web development

Node.js, Ruby on Rails,

2. Ninject

1) Ninject is used to de-couple classed, which known as DI dependency Inject. It is a DI container.

2) Adding Ninject to the Visual Studio Project

  Open NuGet->Online-> search for ninject

3) How to use Ninject to implement DI

Implement Resolver

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web.Mvc; 5 using Ninject; 6 using Ninject.Parameters; 7 using Ninject.Syntax; 8 using System.Configuration; 9 using EssentialTools.Models;10 11 namespace EssentialTools.Infrastructure12 {13     public class NinjectDependencyResolver : IDependencyResolver14     {15         private IKernel kernel;16 17         public NinjectDependencyResolver()18         {19             kernel = new StandardKernel();20             AddBindings();21         }22 23         public object GetService(Type serviceType)24         {25             return kernel.TryGet(serviceType);26         }27 28         public IEnumerable<object> GetServices(Type serviceType)29         {30             return kernel.GetAll(serviceType);31         }32 33         private void AddBindings()34         {35             kernel.Bind<IValueCalculator>().To<LinqValueCalculator>();36             //Create binding with property value37             kernel.Bind<IDiscountHelper>().To<DefaultDiscountHelper>().WithPropertyValue("DiscountSize", 50m);38             39             //Binding when specific condition happened40             kernel.Bind<IDiscountHelper>().To<FlexibleDiscountHelper>()41                 .WhenInjectedInto<LinqValueCalculator>();42         }43     }44 }
View Code

Inject resolver into Global.asax

protected void Application_Start()        {            AreaRegistration.RegisterAllAreas();            DependencyResolver.SetResolver(new NinjectDependencyResolver());            WebApiConfig.Register(GlobalConfiguration.Configuration);            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);            RouteConfig.RegisterRoutes(RouteTable.Routes);        }
View Code

Use DI relationship in Controller

private IValueCalculator calc;        //        // GET: /Home/        public HomeController(IValueCalculator calcParam)        {            calc = calcParam;        }
View Code


3. Moq

It is a dll used to unit testing

 

Pro ASP.NET MVC 4, 4th edition Reading note---Part(1) DI