Thursday, 27 March 2014

Dependency Injection in MVC4

Dependency Injection is a design pattern that helps to reduce tight coupling between software components.
Due to loosely coupled code, we can develop maintainable software systems. Dependency Injection pattern uses an object to initialize the objects and provide the required dependencies to object it allows you to inject a dependency, from outside the class.



DI provides objects that an object needs. So rather than the dependencies construct themselves they are injected by some external means. For instance let’s say we have the following below class “Customer” who uses a “Logger” class to log errors. So rather than creating the “Logger” from within the class, you can inject the same via a constructor as shown in the below code snippet.

 public class Customer
    {
        public Logger Log;
        public Customer(Logger obj)
        {
            Log = obj;
        }

    }

Now we can invoke the customer object with any kind of logger.

Customer obj = new Customer (new EmailLogger());
Customer obj1=new Customer (new EventViewerLogger());

 This approach helps in decoupling. Hence dependency injection helps us in developing testable, maintainable and decoupled software components. There are various tools available for implementing depency injection like Ninject, Unity etc. 



MVC4 Web API - Using Custom Action Names

By default, In MVC Web API, the route configuration follows RESTFUL conventions meaning that it will accept only the Get, Post, Put and Delete action names. However for better readability  a developer will definitely feel the need for his own meaning action names. In this blog, I will explain how to implement custom action names.

1. Let's first create a simple web API. Create ASP.NET MVC4 project by selecting the Web API project template.





2. By default valuescontroller and home controller is added as part of solution.
3. Following methods are added to values controller.
         // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "helloss yogita";
        }

            
3. Run the project, type the url "http://localhost:56355/api/values/" in addess bar. Here is the     response.
                            

4. Similarly, now type the url "http://localhost:56355/api/values/5" and observe the response.


5. Now, these methods are standard methods. But usually, a developer would like to give more logical and meaningful method names. For example, action name Get doesn't reveal much information about what kind of information is returned from a particular action. Let's say I want to call an action GetContactInfo(string id) where id can be EmployeeId.

6. Let's write a method now, in values controller which accepts a Id and returns contact information.
        public string GetContactInformation(string id)
        {
            return "Contact number is 1234567890";
        }
            
7. Now run the project to see what's is returned as output of this method. Type this url "http://localhost:56355/apis/values/GetContactInfo/5"


Oops!!! Ok, this happened because, Web API routing is not aware of this route. 

8. Let's fix it. App_Start->WebApiConfig.cs and provide the route information.

 //declare the route handler for contacts api to handle CustomActionMethod GetContactInfo
            config.Routes.MapHttpRoute(
                name: "ContactsApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

9. Now, we have mapped the route handler with controller and action methods. Now run the project and try                                

Oops!! Its not finding the resource again. 

10. Let's be more specific and provide the actionname information is web uri template as follows.
       //declare the route handler for contacts api to handle CustomActionMethod GetContactInfo
           config.Routes.MapHttpRoute(
                name: "ContactsApi",
                routeTemplate: "api/{controller}/{GetContactInformation}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

           
11. Let's run the URL again. And observe the output.

Therefore we saw how we can use meaningful action names and map them using Web API routing template.