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.Infrastructure
12 {
13     public class NinjectDependencyResolver : IDependencyResolver
14     {
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 value
37             kernel.Bind<IDiscountHelper>().To<DefaultDiscountHelper>().WithPropertyValue("DiscountSize", 50m);
38             
39             //Binding when specific condition happened
40             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

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。