ASP. net mvc controller (2)

Source: Internet
Author: User
Tags define abstract

ASP. net mvc controller (2)

Preface

In the previous sections, text and images are used to represent the Controller activation process. The description is based on the default implementation of the Framework, in this way, everyone can clearly understand the activation process and the object model involved in the process. Today, we will look at what injection points the Framework provides during the activation process, describe it from the perspective of a user.

 

Activate Controller-Injection entry

For example, this is the Controller activation process diagram described in the previous article. It is cited here for fear that some friends have forgotten what they mentioned earlier and have not read the previous article.

 

From the implementation of the default controller factory, in the CreateController () method, the GetControllerType () method is used to obtain the Controller Type, and then transmitted to the GetControllerInstance () method, the implementation is used to generate an IController Based on the Controller Type. The subsequent injection points are also injected in the implementation of the GetControllerInstance () method. The GetControllerInstance () method is the entry point of the entire controller activation process.

IoCExample

Now that we have talked about Dynamic Injection, we must use the IoC framework. We mentioned the use of Ninject in the previous article of MVC. The following example is a demonstration based on Ninject:

1 /// <summary> 2 // product entity class 3 /// </summary> 4 public class Product5 {6 public string ID {get; set ;} 7 public string Name {get; set;} 8}

There is nothing to say about defining a data entity class,

1 /// <summary> 2 // abstract data extraction database 3 /// </summary> 4 public interface IDataStandard 5 {6 List <Product> GetProducts (); 7} 8 // <summary> 9 // default implementation -- Data Extraction Database 10 /// </summary> 11 public class DataProvide: IDataStandard12 {13 14 public List <Product> GetProducts () 15 {16 List <Product> products = new List <Product> () 17 {18 new Product () {ID = "1", Name = "name1"}, 19 new Product () {ID = "2", Name = "name2"}, 20 new Product () {ID = "3", Name = "name3"} 21}; 22 return products; 23} 24}

Here we define an abstract data extraction library and a default implementation as a demonstration for providing data.

1 /// <summary> 2 // call abstract data 3 /// </summary> 4 public interface IDataCall 5 {6 void WriterToMonitor (); 7} 8 9 // <summary> 10 // default data call implementation 11 /// </summary> 12 public class DefultDataCall: IDataCall13 {14 private IDataStandard _ DataStandard; 15 16 public DefultDataCall (IDataStandard dataStandard) // use constructor injection to implement 17 {18 _ DataStandard = dataStandard; 19} 20 21 public void WriterToMonitor () through Ninject framework () 22 {23 foreach (var data in _ DataStandard. getProducts () 24 {25 Console. writeLine ("Prodcut ID:" + data. ID + "Name:" + data. name); 26} 27} 28}

Here we define abstract data calls and default implementations. What we need to do now is to use the IoC framework to decouple call clients from data calls and data extraction,

 1 class Program 2     { 3         static void Main(string[] args) 4         { 5             IKernel ninject = new StandardKernel(); 6             ninject.Bind<IDataStandard>().To<DataProvide>(); 7             IDataCall dataCall = ninject.Get(typeof(DefultDataCall)) as IDataCall; 8             if (dataCall != null) 9             {10                 dataCall.WriterToMonitor();11             }12 13             Console.ReadLine();14         }15     }

Run this Code:

A simple and clear example is run in the MVC project.

 

MVCApplication in projects

As mentioned in the previous chapter, the entry point is protected internal virtual IController GetControllerInstance (RequestContext requestContext, Type controllerType). In the method, we only need to implement a default controller factory Type, and rewrite this method, because we can get the Controller type in the override method, with this function, you can perform a dynamic injection from other objects to the Controller as in the IoC example.

First, we need to define a controller and let it extract library Dependencies from the abstraction in the preceding example, and adopt constructor injection (dependency ).

Take a look at the example:

 1     public class IoCDemoController : Controller 2     { 3         // 4         // GET: /IoCDemo/ 5  6         private IDataStandard _DataStandard; 7  8         public IoCDemoController(IDataStandard dataStandard) 9         {10             _DataStandard = dataStandard;11         }12 13         public ActionResult Index()14         {15             return View(_DataStandard.GetProducts());16         }17     }

Right-click the Index method and choose add view:

Click Add and enter the following code in the View:

@model IEnumerable<ConsoleApplication2.Product>@{    ViewBag.Title = "Index";}

Modify the route settings in the Global. asax file:

1 routes. mapRoute (2 "Default", // route name 3 "{controller}/{action}/{id}", // URL4 new {controller = "IoCDemo" with parameters ", action = "Index", id = UrlParameter. optional} // The default value is 5 );

At this time, the preparation work is well done, but where does the data used in the Controller come from? From our default controller Factory:

 1     public class NinjectControllerFactory :DefaultControllerFactory 2     { 3         private IKernel _NinjectKernel; 4  5         public NinjectControllerFactory() 6         { 7             _NinjectKernel = new StandardKernel(); 8             _NinjectKernel.Bind<IDataStandard>().To<DataProvide>(); 9         }10 11         protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)12         {13             IController controller = _NinjectKernel.Get(controllerType) as IController;14             if (controller != null) 15             {16                 return controller;17             }18             return null;19         }20 21     }

According to the style in the previous chapter, bind the Data Type in NinjectControllerFactory. When the system needs to use the Controller for execution, the data will be dynamically injected into the controller through the Ninject framework.

Finally, you need to set one item:

In the Application_Start () method in the Global. asax file, set our default implemented controller factory to the MVC framework,

1 protected void Application_Start()2         {3             AreaRegistration.RegisterAllAreas();4 5             RegisterGlobalFilters(GlobalFilters.Filters);6             RegisterRoutes(RouteTable.Routes);7             ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());8         }

Add the last sentence of the Code. Now let's take a look at the final effect.

This article will introduce other injection points in the next section.

 

 

 

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.

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.