Slider

Marie Curie Newton Stephen Hawkings APJ Kalam Edison Einstein Gregor Mendel Aryabhatta Ramanujan

Wednesday, 3 December 2014

Dependency Injection in ASP.NET Web API 2

What is Dependency Injection?

A dependency is any object that another object requires. For example, it's common to define a repository that handles data access.
For Dependency injection
we need to create a ScopeContainer(class name may be anything) in App_start folder which should be like this

and also u should install Microsoft.Practices.Unity from nuget package manager
for this PM> Install-Package Unity -Version 3.5.1404


using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Dependencies;

namespace sampleproject.App_Start
{
    public class ScopeContainer : IDependencyResolver
    {
        protected IUnityContainer container;

        public ScopeContainer(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            this.container = container;
        }

        public object GetService(Type serviceType)
        {
            try
            {
                return container.Resolve(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return container.ResolveAll(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return new List<object>();
            }
        }

        public IDependencyScope BeginScope()
        {
            var child = container.CreateChildContainer();
            return new ScopeContainer(child);
        }

        public void Dispose()
        {
            container.Dispose();
        }
    }
}



And call the instances in webapicongig.cs file in app_start folder

namespace sampleproject.App_Start
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "SmartGrocerApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            var container = new UnityContainer();
            container.RegisterType<IShoppingRepository, ShoppingRepository>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new ScopeContainer(container);

        }
    }
}

No comments:

Post a Comment