Application of IoC in ASP. NET Web APIs

Source: Internet
Author: User

Inversion of Control (IoC), simply put, means that the application itself is not responsible for the creation and maintenance of dependent objects, but is responsible for an external container. In this way, the control is transferred from the application to the external IoC container, and the control is reversed. For example, in Type A, instances of type B need to be used, while instance B is not created by A but by external containers. It is of great significance to activate the target HttpController through IoC. [This Article has been synchronized to How ASP. NET Web API Works?]

I. HttpControllerActivator Based on IoC

The purpose of applying IoC to the HttpController activation system is to allow a predefined IoC container to provide the final HttpController object. How is the Controller created through ASP. NET Web API? We know that the activation of HttpController is ultimately completed by the HttpControllerActivator object. Therefore, the most direct way to integrate IoC with the HttpController activation system of ASP. NET Web API is to customize an HttpControllerActivator.

We use a simple example to demonstrate how to integrate with IoC by customizing HttpControllerActivator. The IoC framework we adopt is Unity. The UnityHttpControllerActivator type is defined in an ASP. NET Web API application. UnityHttpControllerActivator has an UnityContainer attribute indicating the Unity container, which is initialized in the constructor. In the Create method of HttpController for creation, we call the Resolve method of this UnityContainer object to Create the target HttpController object.

     
      
       
        
         
          
           
            
             
              
               
                
                 
              

Next, we define the next ContactsController inherited from ApiController to manage contact information. For simplicity, we only define the unique Action method Get to obtain contact information. This method has a default parameter id that indicates the ID of the contact you want to obtain. If this parameter is not provided, a list of all contacts is returned.

                   
                    
                     
                      
                       
                        
                         
                          
                           
                            
                             
                              
                               
                                
                                 
                                  
                                   
                                    
                                     
                                      
                                       
                                    

The Action method uses the objects returned by the Repository attribute to implement the contact query. attributes of this IContactRepository interface type are initialized in the constructor. We use the IContactRepository interface to abstract the storage of contact data, as shown in the following code snippet. In this interface, we only define the unique GetContacts method to filter the corresponding contact list based on the specified addition.

                                         
                                          
                                           
                                        

We have defined the next defacontcontactrepository type as the default implementer of the IContactRepository interface. For simplicity, we use a static dictionary to save the contact list.

                                             
                                              
                                               
                                                
                                                 
                                                  
                                                   
                                                    
                                                     
                                                      
                                                       
                                                        
                                                     

We registered the custom UnityHttpControllerActivator in Global. asax. As shown in the following code snippet, we created an UnityContainer object in the Application_Start method and called the generic method RegisterType <TFrom, register> registers the matching relationship between the IContactRepository interface and the DefaultContactRepository type. Finally, we create an UnityHttpControllerActivator object based on this UnityContainer and register it to the current ServicesContainer.

                                                          
                                                           
                                                            
                                                             
                                                              
                                                               
                                                                
                                                                 
                                                                  
                                                               

When this ASP. after the Web API application is running, you can enter the corresponding address in the browser to obtain the list of all contacts ("/api/contacts ") and for a contact whose ID is "001" ("/api/contacts/001"), the corresponding contact information will appear in the browser as shown in.

Ii. IoC-based DependencyResolver

Because the default DefaultHttpControllerActivator will first use the currently registered DependencyResolver object to activate the target HttpController, in addition to introducing IoC into the HttpController activation system using the custom HttpControllerActivator, another effective solution is to register a custom DependencyResolver.

The DependencyResolver to be customized is based on another IoC framework called "Ninject. Ninject is a more lightweight IoC framework than Unity. Due to space limitations, we cannot provide much introduction to this IoC framework. If you are interested, visit its official website ("http://www.ninject.org/") to learn about Ninject.

                                                                    
                                                                     
                                                                      
                                                                       
                                                                        
                                                                         
                                                                          
                                                                           
                                                                            
                                                                             
                                                                              
                                                                               
                                                                                
                                                                                 
                                                                                  
                                                                                   
                                                                                    
                                                                                     
                                                                                      
                                                                                       
                                                                                        
                                                                                         
                                                                                          
                                                                                           
                                                                                            
                                                                                             
                                                                                              
                                                                                               
                                                                                                
                                                                                                 
                                                                                                  
                                                                                                   
                                                                                                    
                                                                                                     
                                                                                                      
                                                                                                       
                                                                                                        
                                                                                                         
                                                                                                          
                                                                                                           
                                                                                                            
                                                                                                             
                                                                                                              
                                                                                                               
                                                                                                                
                                                                                                                 
                                                                                                                  
                                                                                                                   
                                                                                                                    
                                                                                                                     
                                                                                                                      
                                                                                                                       
                                                                                                                        
                                                                                                                         
                                                                                                                          
                                                                                                                       

We have created a custom DependencyResolver of the above Type NinjectDependencyResolver. The core of NinjectDependencyResolver is the read-only attribute of the IKernel. The GetService and GetServices methods used to obtain the service instance are implemented by calling the TryGet and GetAll methods of this Kernel attribute. The BeginScope method returns a new NinjectDependencyResolver object, which has the same Kernel object as itself. We have defined an additional method Register <TFrom, Register> to Register the ing between interfaces and implementation types. To ensure that the retrieved service instance can be released normally, we define a list with the element type IDisposable. If the obtained object implements the IDisposable interface, it will be put into this list, and all objects in this list will be released in the implemented Dispose method.

Now we apply this custom NinjectDependencyResolver to the previous demo instance. We only need to replace the registration for custom HttpControllerActivator in Global. asax with the registration for NinjectDependencyResolver. After you run this ASP. NET Web API application, you can use a browser to obtain the contact information, as shown in.

                                                                                                                            
                                                                                                                             
                                                                                                                              
                                                                                                                               
                                                                                                                                
                                                                                                                                 
                                                                                                                                  
                                                                                                                                   
                                                                                                                                    
                                                                                                                                 

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.