Sunday, June 7, 2015

IOC in Web API

Inject Dependency in WebAPI using Unity IoC container

I had a misconception about Unity IoC container. I was trying to manage dependency of one Api Controller using Unity container, which was specific for MVC. So, In obvious reason It did not worked.

Then I checked in Google and realize that Unity has different package for  WebAPI. If you are interested to inject dependency in WebAPI controller , please use following package.

Install-Package Unity.AspNet.WebApi -Version 3.5.1404

It will scaffold necessary setting in your application. In this article we will see where to register your dependency in  for API controller.

Here is unity Activator class which will automatically generate for you.

public static class UnityWebApiActivator
    {
        /// <summary>Integrates Unity when the application starts.</summary>
        public static void Start()
        {
            var resolver = newUnityDependencyResolver(UnityConfig.GetConfiguredContainer());
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }

        public static void Shutdown()
        {
            var container = UnityConfig.GetConfiguredContainer();
            container.Dispose();
        }
    }

The Start and ShutDown functions are to up and down container in application. Here is definition of UnityConfig class.

    public class UnityConfig
    {
        #region Unity Container
        private static Lazy<IUnityContainer> container = newLazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });
        /// <summary>
        /// Gets the configured Unity container.
        /// </summary>
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion

        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterType<IServiceService>();
        }
    }

The RegisterType function is important one. Here we have to register our dependency. In this example we will implement IService interface in Service class and will inject to API Controller. For that, we are registering Dependency here.

Create controller to inject dependency.

public interface IService
    {
        void hello();
    }
    public class Service : IService
    {
        void IService.hello()
        {
            throw new NotImplementedException();
        }
    }

    public class DummyController : ApiController
    {
        IService obj;
        public DummyController(IService obj)
        {
            this.obj = obj;
        }
       
        public void Get()
        {

        }
    }

Once we invoke Dummy controller ,we will see that Dependency has injected to constructor.




Send data through HTTP request BODY and URI

We know that every HTTP request/response has two sections. Head and body. The head section contains information, which represents the information about current http request. The body section contains data in general.
There are two ways to send data to server using HTTP request. One is through url which will carry in head section or through Body which will encode data in string format and embed it in http body section.

Generally, when we perform Get HTTP request to server, the client agent attach data through uri and thus pass data to server through header section.

However, when we make HTTP Post request, the client agent encode data and attach it in body section of request. As the data passes through body section, it is not visible to end user.

It does not mean that the data or HTTP request is very much secure. Because when data is encoded, it encodes in plain string format and easily anyone can decode it. The solution is to use HTTPS protocol.

Now, it’s not necessary to pass data from uri or request body depending on nature of request. I mean, we can send data through url even it is Post request. We will test it on ASP.NET MVC framework using Fiddler as client agent.

Pass data through URI

Here we will pass data through URI even it is Post type HTTP request. Here is sample code

   public class DummyController : ApiController
    {
       public void Post([FromUriObject data)
       {
          
       }
       
    }

We are seeing that the data will come as object format and “FromUri” attribute has specified before parameter.


Once we hot on to Action , we will see that the data has came in parameter.


Now, how we will make sure that data has pass through URI not Body ? If we open the http request in Inspectors tab in fiddler, we will see the transformed URI and data is getting pass as query string.


Now, we will try to pass data through body of HTTP request.  For that we have to make little change in code. Here is modified code. Just we have change the “FromUri” attribute to “FromBody” attribute.

public class DummyController : ApiController
    {
       public void Post([FromBodyObject data)
       {
          
       }
       
    }

And if we generate one http Post request by specifying data in http body ,we will see that the data has embedded in body section of http request.


So, the conclusion is, there is complete freedom to choose way to send data in http request irrespective of method type.

No comments:

Post a Comment