Preliminary understanding of the Ninject of ASP. NET MVC Preschool

Source: Internet
Author: User

Preliminary understanding of the Ninject of ASP. NET MVC Preschool

1. Introduction

Nonsense, Ninject is a lightweight, basic. NET an open-source IOC framework that uses the IOC framework for the study of the MVC framework, because there are a lot of this open-source framework, the only one topic in this article is to let friends who have read this space know the role of the IOC framework in the project and its importance. The purpose of this is to choose an IOC framework that you want to learn, use, or implement yourself in a future learning job. All right, no more nonsense.

2. Environmental preparedness

1. Create a 4.0Framework console Application project with the name Iocdemo

2. In the Http://www.ninject.org/download Web page, download version 2.2 Ninject assembly (previous version does not support 4.0 libraries), download completed decompression will see a few files in 1, Here you only need to care about files named Ninject, others are ignored.

Figure 1

650) this.width=650; "src=" Http://images.cnitblog.com/i/627988/201406/022224256451966.png "/>


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

Figure 2

650) this.width=650; "src=" Http://images.cnitblog.com/i/627988/201406/022225202706311.png "/>

The environment is ready to do a good job, you can safely look at the example. Incidentally, Ninject.xml file is an assembly file comments, but all in English, for the posture of the low-level cock silk is not a welfare, of course, including myself. (PS: Google Translate something very useful)

3. Preliminary knowledge and understanding

From the previous article, it is possible to understand a basic IOC, which is to be considered in the perspective of the container object, and the concrete implementation object can be injected into the container object dynamically. Let's take a look at the new example and find out where the last one is, and look at the problem in a different way.

We first define a product class that contains only the number, name, and price of the product three attributes

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 define the pricing specification for the goods and a basic implementation of it.

Code 3-2

 1     /// <summary> 2     ///  Commodity Pricing Specification  3     /// </summary> 4      public interface ivaluation 5     { 6          float commodityvaluation (params commodity[] commodities);  7      } 8  9     /// <summary>10      ///  Commodity Pricing Specification Implementation one: The total price of goods 11     /// </summary >12     public class commoditysumvaluation : ivaluation13      {14         public float  Commodityvaluation (params commodity[] commodities) 15          {16             return commodities. Sum (commodity => commodity. Price); 17         }18     }

So it seems that posture and the same on the previous paragraph is really similar, do not worry slowly to see. The container object is defined and decoupled through the construction injection, allowing the container object to be completely detached from the concrete implementation.

Code 3-3

 1     /// <summary> 2     ///  Shopping Cart-Container objects  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, standing at different angles to define the result is different, if you stand in the perspective of the container object, it is true that the realization of understanding coupling, 3

Figure 3

650) this.width=650; "style=" width:730px;height:231px; "src=" http://images.cnitblog.com/i/627988/201406/ 022229150363623.png "width=" 711 "height=" 181 "/>

You can clearly see that the ShoppingCart type (container) and the Commoditysumvaluation type (Implementation) do not have any relationship to achieve decoupling, but the problem is to be combined to actually call the container object from the client view:

Code 3-4

1 namespace Iocdemo 2 {3 class program 4 {5 static void Main (string[] args) 6 {7 Sh Oppingcart ShoppingCart = new ShoppingCart (new Commoditysumvaluation ()); 8 9}10}11}

Code see here, presumably everyone will have a headache, this whole call what matter, spare a circle or coupling. 4

Figure 4

650) this.width=650; "style=" width:741px;height:266px; "src=" http://images.cnitblog.com/i/627988/201406/ 022232463178508.png "width=" 825 "height=" 229 "/>

In this case the IOC framework can be useful, this article is about Ninject, which of course is used ninject, according to the previous 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 frame 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 is the binding of the Ivaluation type through the Ikernel type of the bind generic method in Ninject, which is represented by the type in the to generic method as an implementation of the type in the Bind method, so that the kernel. Get<ivaluation> () is the type of commoditysumvaluation returned. Here the use of ninject is not much to introduce, but to focus on explaining the importance of the IOC and its role.

This time the dependency structure like 5

Figure 5

650) this.width=650; "style=" width:738px;height:261px; "src=" http://images.cnitblog.com/i/627988/201406/ 022234396928238.png "width=" 623 "height=" 187 "/>

This may not see the IOC effect, we add some additional requirements, and change the Commoditysumvaluation implementation class,

Code 3-6

 1     /// <summary> 2     ///  Pricing Discount Algorithm Specification  3     /// </summary> 4      public interface ivaluationdiscount 5     { 6          float valuationdiscount (Float listprice); 7      } 8  9     /// <summary>10      ///  Pricing Discount Algorithm specification implementation one: 90 percent   walk up 11     /// </summary>12      public class DisCount : IValuationDisCount13      {14 15         public float  Valuationdiscount (Float listprice) 16         {17              return listprice -  (listprice * 10 / 100); 18          }19     }

Add a new requirement specification and a new implementation class, so that the sum of the goods can be discounted, but also in the Commoditysumvaluation implementation class to implement the construction injection, modify the code as follows:

Code 3-7

 1     /// <summary> 2     ///  Commodity pricing Specification Implementation one: Total price of goods  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 there is no IOC framework at this time, look at how the client is called:

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 } 

Running a bit can also get results, but no matter how abstract, the client calls need to be directly dependent on the implementation class, rather than the high-level abstraction,

Figure 7

650) this.width=650; "style=" width:738px;height:181px; "src=" http://images.cnitblog.com/i/627988/201406/ 022238017551973.png "width=" 697 "height="/>

It can be seen how horrible it is. Re-modify the code in the main function 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 frame function 10              ikernel kernel = new standardkernel ();11              kernel. Bind<ivaluation> (). To<commoditysumvaluation> ();12              kernel. Bind<ivaluationdiscount> (). To<discount> ();13              Ivaluation valuation =&nBsp;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

650) this.width=650; "src=" Http://images.cnitblog.com/i/627988/201406/022239150831306.png "/>

Look again at the dependency structure,

Figure 9

650) this.width=650; "style=" width:745px;height:213px; "src=" http://images.cnitblog.com/i/627988/201406/ 022240407701827.png "width=" 756 "height=" 213 "/>

The Ninject framework examines all types that are dependent on the type being returned, and is also injected dynamically into the type.
From the comparison between Figure 7 and Figure 9, it can be seen that only by adding the IOC framework to the client and the implementation of the decoupling, without the addition of the middle tier is not really good to achieve the elimination of coupling, and the IOC framework can be dynamically configured.
This is the end of this article, to Ninject interested friends please learn it by yourself.

This article is from the "Jinyuan" blog, please be sure to keep this source http://jinyuan.blog.51cto.com/8854733/1423570

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.