Use mvc4, ninject, EF, Moq to build a real application of e-commerce sportsstore (2)

Source: Internet
Author: User
In the previous article, we established a basic project framework. if you carefully study this framework, you must have discovered that we have actually used a domain model to replace the model in MVC, why? In the old three-tier architecture of MVC, M is designed to provide data to the Controller and encapsulate the business logic. C is calling view to display data to users. In turn, the user sends his or her intent to C by triggering some view events, and C resends the user's command line m to obtain the user's desired results. This is an ideal state. In real projects, m often bypasses C and calls V directly, while view directly calls M. This leads to the emergence of a wrong and chaotic data stream, which is the root cause of increasing project risks. MVP was created to overcome this phenomenon. Well, we don't care about any MVP or mvvm. Now let's get down to the truth and return to our project to continue to show the highlights and charm of MVC. We know that we need some ways or methods to obtain the product entities in the database. To keep the architecture perfect, we must follow the principle of separation of the persistent logic and the entity of the domain model. To achieve this, we use the Repository design pattern. we don't need to worry about how to implement the persistent layer. We start an interface by defining it. Right-click the abstract folder and select Add an interface named iproductsrepository, Code As follows:
  using   system;   using   system. collections. generic;   using   system. LINQ;   using   system. text;   using   system. threading. tasks;   using   sportsstore. domain. entities;   namespace   sportsstore. domain. abstract {  Public   interface   iproductsrepository {iqueryable  
  
    Products {
    Get  
   ;}} 
  

This excuse uses the iqueryable <t> interface to get a product object. We didn't tell it where to go or how to get data. A class that uses the iproductsrepository interface can get the product object, without knowing where they come from or who will pass them, this is the essence of the Repository design pattern. Next, we will add some features to our code to visit this interface again. Building a mock repository now we have defined an abstract interface. We can implement this persistence mechanism and connect it to the database. However, this is not what we need to do now. In order to start other parts of this project, now we want to create a mock Implementation of iproductsrepository interface. We need to go to our sportsstore. do this in the addbindings method of the ninjectcontrollerfactory class of the webui project. Using system; using system. Collections. Generic; using system. LINQ; using system. Web; Using system. Web. MVC; Using system. Web. Routing; Using sportsstore. domain. abstract; Using sportsstore. domain. entities; Using Moq; Using ninject; Namespace sportsstore. webui. infrastructure {public class kernel: kernel {private ikernel ninjectkernel; Public kernel () {kernel = new standardkernel (); kernel () ;}protected override icontroller getcontrollerinstance (requestcontext, type controllertype) {return controllertype = NULL? Null: (icontroller) ninjectkernel. Get (controllertype);} private void addbindings (){ Mock <iproductsrepository> mock = new mock <iproductsrepository> (); Mock. Setup (M => M. Products). Returns (new list <product> { New product {name = "football", price = 25 }, New product {name = "surf board", price = 179 }, New product {name = "running shoes", price = 95} }. Asqueryable ()); Ninjectkernel. Bind <iproductsrepository> (). toconstant (Mock. Object ); } To make the added code run properly, several namespaces need to be added. However, Moq technology is used to create the mock repository implementation process, the asqueryable method is a LINQ extension method that converts ienumerable <t> to iqueryable <t>. here we need to match the signature of our interface. No matter where iproductsrepository receives a request, we need ninject to return the same mock object, which is why we use the toconstant method .... Ninjectkernel. Bind <iproductrepository> (). Toconstant (Mock. Object) ;... Display product list After so long, we haven't seen any visualization results yet. This is unfair to some impatient friends and we can't see any achievements, it will strike down our confidence in the project, which is not good for the development team. Now let's add a controller to sportsstore. in the webui project, select Add controller and name it productcontroller. Make sure that the template selection is empty. For example, delete the code automatically added by Vs and replace it with the following code: using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. MVC; using sportsstore. domain. abstract; using sportsstore. domain. entities; namespace sportsstore. webui. controllers {public class productcontroller: controller {private iproductsrepository repository; Public productcontroller (iproductsrepository productrepository) {This. repository = productrepository;} public viewresult list () {return view (repository. products) ;}} if your project is in using sportsstore. domain. abstract: This statement has an error. You need to add the statement to the sportsstore. domain project reference, such: To add a view, right-click the list method and select add view, Note that you cannot find the ienumerable <sportsstore. domain. Entities. Product> item in the drop-down list of the model class. You need to enter it manually. Click Add to create a view. Rendering View data @ Model ienumerable <sportsstore. domain. Entities. Product> @ {viewbag. Title =   "Products "; } @ Foreach (var p in Model ){ <Div class = "item"> <H3> @ P. Name @ P. Description <H4> @ P. Price. tostring ("C") </H4> </Div> } Let's change the title of this page. Note that we do not need to use razor text or @: elements to display data here, because each line of content is an HTML element. Set default route What we need to do now is to tell the MVC framework that when a request arrives, our website will map

The list activity method of the productcontroller class. You need to modify

The code of the registerroutes method is as follows:

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. MVC; using system. web. routing; namespace sportsstore. webui {public class routeconfig {public static void registerroutes (routecollection routes) {routes. ignoreroute ("{resource }. axd/{* pathinfo} "); routes. maproute (name: "default", URL: "{controller}/{action}/{ID}", defaults: New {controller =" Product ", Action =" List ", Id = urlparameter. optional}) ;}}after the modification is completed, run your application and you will see the following picture: You can download my source code: this part of the http://vdisk.weibo.com/s/DS1PL/1370071350 we show our application, using part of the Moq technology and ninject technology, but our current data is only the simulation data in the mock object, not the real data in the database, in the next section, we will introduce the EF framework to learn more about ORM Data operations. If you think that I have worked hard and you think you have got what you want, please recommend it to others who need it! Please keep an eye on my remaining articles. It's just the beginning!
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.