Introduction to Ninject in ASP. NET MVC

Source: Internet
Author: User

Introduction to Ninject in ASP. NET MVC

1. Introduction

Ninject is a lightweight and basic tool. NET, an open-source IoC framework, will be used in the learning of MVC frameworks, because there are many such open-source IoC frameworks, there is only one topic in this article, it is to let friends who have read this article to tease them about the role of the IoC framework in the project and its importance. In this way, you can select an IoC framework to learn, use, or implement it on your own. Okay, no nonsense.

 

2. Prepare the environment

1. Create a console application project named IoCDemo for 4.0Framework.

2. download the Ninject assembly of Version 2.2 From the http://www.ninject.org/downloadweb page (the previous version does not support library 4.0). After downloading and unzipping, several files in Section 1 are displayed, here, you only need to care about the file named Ninject, while others are ignored.

Figure 1

 


3. Create a Lib folder in the project, copy Ninject. dll, Ninject. pdb, and Ninject. xml to the file directory, and add references to the project. 2:

Figure 2

The environment is ready, so you can look at the example with peace of mind. The Ninject. xml file is the annotation of the Assembly file, but it is in English. It is not a benefit for the poor posture, of course, it also includes myself. (Ps: Google Translate is useful)

3. Preliminary understanding and understanding

From the previous article, we can understand a basic IoC, which is taken into account from the perspective of the container object. The specific implementation object can indeed be dynamically injected into the container object. Let's take a look at the new example and find the shortcomings in the previous article to look at the problem from another angle.

First, we define a commodity class. The content only contains three attributes: Product ID, name, and price.

Code 3-1

1 /// <summary> 2 // goods 3 /// </summary> 4 public class Commodity5 {6 public string CommodityID {get; set ;} 7 public string Name {get; set;} 8 public float Price {get; set;} 9}

After the product type is defined, we will define the pricing specification of a product and its basic implementation.

Code 3-2

1 // <summary> 2 // goods pricing specification 3 /// </summary> 4 public interface IValuation 5 {6 float CommodityValuation (params Commodity [] commodities ); 7} 8 9 // <summary> 10 // goods pricing specification Implementation 1: Total commodity prices 11 /// </summary> 12 public class CommoditySumValuation: IValuation13 {14 public float CommodityValuation (params Commodity [] commodities) 15 {16 return commodities. sum (commodity => commodity. price); 17} 18}

In this case, the architecture is the same as that in the previous article. The previous section is indeed similar, so don't worry about it. Define a container object and construct the injection method to implement decoupling, so that the container object and the specific implementation are completely separated.

Code 3-3

1 /// <summary> 2 // shopping cart-container object 3 /// </summary> 4 public class ShoppingCart 5 {6 private IValuation _ Valuation; 7 public ShoppingCart (IValuation valuation) 8 {9 _ Valuation = valuation; 10} 11 12 public float CommodityTotalPrice () 13 {14 Commodity [] commodities = 15 {16 new Commodity () {CommodityID = "A1", Price = 14}, 17 new Commodity () {CommodityID = "A2", Price = 76.5f}, 18 new Commodity () {CommodityID = "B2", Price = 34.4f}, 19 new Commodity () {CommodityID = "C4", Price = 23.1f} 20}; 21 22 return _ Valuation. commodityValuation (commodities); 23} 24}

For the definition of the above sentence, the results are different from different perspectives. if the definition is from the perspective of the container object, it is indeed achieved decoupling, 3

Figure 3

We can clearly see that the ShoppingCart type (container) and CommoditySumValuation type (specific implementation) have no relationship, so as to achieve the goal of decoupling, however, the problem should be solved based on the actual situation:

Code 3-4

 1 namespace IoCDemo 2 { 3     class Program 4     { 5         static void Main(string[] args) 6         { 7             ShoppingCart shoppingCart = new ShoppingCart(new CommoditySumValuation()); 8  9         }10     }11 }

When the code sees this, it may be a headache for everyone. What is the whole thing? It's still coupling after a lap. 4

Figure 4

In this case, the IoC framework can be used. This article introduces Ninject, which of course uses Ninject. According to the preceding environment configuration,

Code 3-5

1 using Ninject; 2 3 namespace IoCDemo 4 {5 class Program 6 {7 static void Main (string [] args) 8 {9 # region IoC framework function 10 IKernel kernel = new StandardKernel (); 11 kernel. bind <IValuation> (). to <CommoditySumValuation> (); 12 IValuation valuation = kernel. get <IValuation> (); 13 # endregion14 15 ShoppingCart shoppingCart = new ShoppingCart (valuation); 16 Console. writeLine (shoppingCart. commodityTotalPrice (). toString (); 17 Console. readLine (); 18} 19} 20}

Here, we use the Bind generic method of the IKernel type in Ninject To Bind the IValuation type. The type in the To generic method is the implementation of the type in the Bind method. get <IValuation> () is the CommoditySumValuation type returned. The usage of Ninject is not described here, but mainly explains the importance and function of IoC.

The dependency structure at this time is as follows: 5

Figure 5

In this way, we may not see the effect of IoC. We will add some new requirements and change the CommoditySumValuation implementation class,

Code 3-6

1 /// <summary> 2 // billing discount Algorithm specification 3 /// </summary> 4 public interface IValuationDisCount 5 {6 float ValuationDisCount (float listPrice ); 7} 8 9 // <summary> 10 // billing DisCount Algorithm specification Implementation 1: Off 11 /// </summary> 12 public class DisCount: IValuationDisCount13 {14 15 public float ValuationDisCount (float listPrice) 16 {17 return listPrice-(listPrice * 10/100); 18} 19}

A new requirement specification and a new implementation class are added, so that the total commodity quantity can be discounted. You also need to implement constructor injection in the CommoditySumValuation implementation class. The modified code is as follows:

Code 3-7

1 // <summary> 2 // goods pricing specification Implementation 1: Total commodity prices 3 /// </summary> 4 public class CommoditySumValuation: IValuation 5 {6 private IValuationDisCount valuationDisCount; 7 8 public CommoditySumValuation (IValuationDisCount valuationdiscount) 9 {10 this. valuationDisCount = valuationdiscount; 11} 12 13 public float CommodityValuation (params Commodity [] commodities) 14 {15 return valuationDisCount. valuationDisCount (commodities. sum (commodity => commodity. price); 16} 17}

If the IoC framework does not exist at this time, check how the client calls it:

Code 3-8

 1 using Ninject; 2  3 namespace IoCDemo 4 { 5     class Program 6     { 7         static void Main(string[] args) 8         { 9             ShoppingCart shoppingCart =10                 new ShoppingCart(new CommoditySumValuation(new DisCount()));11 12             Console.WriteLine(shoppingCart.CommodityTotalPrice().ToString());13             Console.ReadLine();14         }15     }16 }

The results can also be obtained after running. However, no matter how abstracted, client calls must depend on implementation classes rather than high-level abstractions,

Figure 7

We can see how terrible this is. Modify the code in the Main function again to use the IoC framework.

Code 3-9

1 using Ninject; 2 3 namespace IoCDemo 4 {5 class Program 6 {7 static void Main (string [] args) 8 {9 # region IoC framework function 10 IKernel kernel = new StandardKernel (); 11 kernel. bind <IValuation> (). to <CommoditySumValuation> (); 12 kernel. bind <IValuationDisCount> (). to <DisCount> (); 13 IValuation valuation = kernel. get <IValuation> (); 14 # endregion15 16 ShoppingCart shoppingCart = new ShoppingCart (valuation); 17 18 Console. writeLine (shoppingCart. commodityTotalPrice (). toString (); 19 Console. readLine (); 20} 21} 22}

Result 8:

Figure 8

Let's take a look at the dependency structure,

Figure 9

The Ninject framework checks all types that the returned types depend on and dynamically injects them into the types.
From the comparison in Figure 7 and Figure 9, we can see that only the IoC framework is added to decouple the client from the specific implementation. without the addition of this intermediate layer, it is really difficult to eliminate coupling, the IoC framework can also be dynamically configured.
This article ends here. If you are interested in Ninject, Please study it on your own.

 

 

Author: Jin Yuan

Source: http://www.cnblogs.com/jin-yuan/

The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and go to the Article Page.

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.