Learning notes for Pro ASP. net mvc 3 Framework

Source: Internet
Author: User
Tags to domain

 

This note is divided into three parts: Ninject (dependency injection container, which is described earlier. If you pass by here for the first time, you can take a look at my previous notes ), NUnit (Unit Testing Tool) and Moq (used to simulate the implementation of interfaces in unit testing ). my note today is about the first part: Ninject.

 

If you do not know anything about dependency injection (DI), you can take a look at my previous notes or search for relevant materials online. Next we will use an example to introduce how to use Ninject. First, we need to slam here to download the relevant DLL. We still use the previous Product to realize the total value of all the products of the technology. The following describes the procedure in detail:

 

1. Create a Console Application. If you don't mind, name it NinjectDemo. Next, create a Product class, as shown below:

 

Namespace NinjectDemo

{

Public class Product

{

Public int ProductID {get; set ;}

Public string Name {get; set ;}

Public string Description {get; set ;}

Public decimal Price {get; set ;}

Public string Category {set; get ;}

}

}

 

Create an IValueCalculator interface, as shown below:

 

Namespace NinjectDemo

{

Public interface IValueCalculator

{

Decimal ValueProducts (params Product [] products );

}

}

 

Create an interface implementation, as shown below:

 

Namespace NinjectDemo

{

Public class LinqValueCalculator: IValueCalculator

{

Public decimal ValueProducts (params Product [] products)

{

Return products. Sum (p => p. Price );

}

}

}

 

Here we calculate the total price of Products using the extension method of LINQ (for the extension method described in the previous note), of course, here you can traverse the sum of Products and return a Decimal type value. Next we will create a class to implement dependency injection. ShoppingCart. cs:

 

Public class ShoppingCart

{

Private IValueCalculator calculator;

Public ShoppingCart (IValueCalculator calcParam)

{

Calculator = calcParam;

}

 

Public decimal CalculateStockValue ()

{

Product [] products = {

New Product () {Name = "Kayak", Price = 275 M },

New Product () {Name = "Lifejacket", Price = 48.95 M },

New Product () {Name = "Soccer ball", Price = 19.50 M },

New Product () {Name = "Stadium", Price = 79500 M}

};

Decimal totalValue = calculator. ValueProducts (products );

Return totalValue;

}

}

 

2. the dependency Injection used here is a Constructor Injection (Constructor Injection) introduced in the previous notes ), the instances implemented through the interface are passed as parameters to the ShoppingCart constructor to decouple ShoppingCart and LinqValueCalculator (IValueCalculator interface implementation. The following figure illustrates the direct relationship between these classes or interfaces as follows:

 

 

In fact, in my own understanding, the decoupling operation is to introduce a "third party" between two coupled objects, so that our goal is achieved. Of course, in the program, I often need such a "third party", but not in real life. The analogy here is not very appropriate. You should not go into it. ShoppingCart and LinqValueCalculator both depend on IValueCalculator, but they are not directly related to each other, or even do not know the existence of each other. I can change the implementation of LinqValueCalculator, or simply implement the IValueCalculator interface in other ways, instead of making ShoppingCart aware, because it is no longer so intelligent.

 

3. From the relationships between the above classes and interfaces, we can find that ShoppingCart, IValueCalculator, and LinqValueCalculator are directly related to the Product. We don't need to worry, because the Product here is equivalent to Domain Model Type, and I expect strong coupling between such classes and other parts of the application. Of course, if we do not create an MVC program, we may have different opinions and may also adopt decoupling operations for the Product.

 

4. Our goal is to create a ShoppingCart instance and inject it using the IValueCalculator implementation as the constructor parameter. This is exactly the role that Ninject (DI container) plays for us. Before we use Ninject, I first introduce Ninject. dll, and check the properties of some of our projects to determine if our Target Framework is. NET Framework 4, if it is. NET Framework 4 Client Profile. An error will be reported later during compilation, indicating that there is no Ninject namespace. The reason is that the Client Profile ignores Ninject. dll.

 

5. For Ninject usage, we can use the following code (Console Application's Program. cs:

 

Static void Main (string [] args)

{

IKernel ninjectKernel = new StandardKernel ();

NinjectKernel. Bind <IValueCalculator> (). To <LinqValueCalculator> ();

// Obtain interface implementation

IValueCalculator calcImpl = ninjectKernel. Get <IValueCalculator> ();

 

// Create a ShoppingCart instance and inject Dependencies

ShoppingCart cart = new ShoppingCart (calcImpl );

 

// Execute

Console. WriteLine ("Tatol: {0: c}", cart. CalculateStockValue ());

 

}

 

Next we will introduce the bold code. Using Ninject, we will first create an IKernel object to interact with Ninject. Once we create an IKernel object, we need to perform two operations through Ninject. First, bind the interface type we want to create. Here we want to tell Ninject that when we receive the interface implementation request, we will create a LinqValueCalculator instance for us and return it to us. Here we use the Bind <T> ()... To <T> () method defined in the IKernel. As in the Code: ninjectKernel. Bind <IValueCalculator> (). To <LinqValueCalculator> (); then we have completed the registration (the preceding notes mentioned the use of DI containers ). Second, use the Get () method of Ninject to create the object implemented by the interface. This is what I need to pass as a parameter to the ShoppingCart constructor. Remember! Hey!

 

Okay. Let's sort out some ideas. First, we are decoupling and passing the objects implemented by IValueCalculator to ShoppingCart as parameters. Next, we manage and obtain this parameter through the DI container, and we implement it through Ninject. Here we should have some knowledge about Ninject.

 

Well, today's note is here. We will learn more about Ninject usage tomorrow.

 

For beginners of MVC and lame English, there must be some inaccuracy and errors in the notes. Please help me more! Thank you!

 

Good night!


 

Author Gabriel Zhang

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.