Showing posts with label Unity container. Show all posts
Showing posts with label Unity container. Show all posts

Tuesday, March 19, 2019

Install Unity in Web API

This blog discuss about the unity and its feature and it demonstrates how to install unity in web api project by using nugget package and explain about the type mapping registration

Unity Container :

The Unity is a full feature, a light weight, extensible dependency injection container, it helps to build the loosely coupled program and simplified object creation.

Unity Container Features:

1.       Abstraction the dependency of program and on demand it injects dependency.
2.       Simplified type-mapping registration for interface type or base type.
3.       Automatically injects registered type at run-time through constructor, property or method.
4.       Automatically manages the scope of instance and if it goes outside scope, it automatically dispose the instance.


Installation of Unity in Web API Project:

Here are steps to install unity package in our web API application.

1.       Open the nuget package manager



2.       Search ‘Unity’ package


3.       Click on install button to install unity package.

Unity.WebAPI package allows the simple Integration of the Unity IoC container with ASP.NET Web API. 

Here are steps to install unity.WebAPI package in our web api application.

1.       Open the nuget package manager
2.       Search ‘Unity.WebAPI’ package
3.       Click on install button to install unity.webapi package.


after two packages installations, there are few dll reference are added into project 



after unity.webapi package installation, the UnityConfig.cs class file is added under App_Start folder. 



In UnityConfig file, it contains the mapping for register types eg ( IOrderEngine ) and having information dependence resolver ( we are using Unity.WebAPI assembly as resolver)


C# Code :

public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();
           
            container.RegisterType<IOrderEngine, OrderEngine>();
           
            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    }


Add line in Global.asax.cs to configure unity container

C# Code :

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            UnityConfig.RegisterComponents();  ß------------ Add line
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }



OrdersController is WEB API  Controller, which create and update the order information. You can see, the IOrderEngine type is being passed as parameter into API controller’s constructor and when API constructor is being called; it uses unity to resolve the IOrderEngine type.

C# Code :

    [RoutePrefix("api/Orders")]
    public class OrdersController : ApiController
    {
        IOrderEngine _orderEngine;

        public OrdersController(IOrderEngine orderEngine)
        {
            _orderEngine = orderEngine;
        }

        [HttpPost]
        [ApiVersion("1.0", Deprecated = true)]
        [ApiVersion("2.0")]
        [Route("v{version:apiVersion}/Create")]
        public IHttpActionResult Create(Order Order)
        {
            return Ok(_orderEngine.Create(Order));
        }

        [HttpPut]
        [ApiVersion("1.0", Deprecated = true)]
        [ApiVersion("2.0")]
        [Route("v{version:apiVersion}/Update")]
        public IHttpActionResult Update(Order Order)
        {
            return Ok(_orderEngine.Update(Order));
        }

    }

other dependency injection and unity container  related posts : 

Friday, January 4, 2019

Unity Container Register Singleton Class

In C#, there are several way to maintain the single instance of object by using singleton pattern, static classor static property with private constructor.

Singleton Pattern HTTPCLient

Recently I explored one more way to implement singleton pattern by using unity and in unity container, we can define the lifetime scope of object instance by passing Lifetime Manager option in RegisterType methods.

  UnityContainer container = new UnityContainer();

 container.RegisterType<IHTTPClientManager, HTTPClientManager>(new ContainerControlledLifetimeManager());

In above example, ContainerControlledLifetimeManager as Lifetimemanager option is being passed in registerType method for IHTTPClientManager type.

Unity will take care of instance creation of  IHTTPClientManager type and it will make sure that there will be a single instance of IHTTPClientManager type.it will not create any new instance after first resolve method call and it will share same instance.

Wednesday, February 28, 2018

Unity Container Lifetime Scope of Instance of Registered Type

In this blog, we will discuss about lifetime scope of instance of register type created by Unity Container and how to manage it

Container.RegisterInstance(typeof(ProjectEngine), new ProjectEngine ())

By default, the RegisterInstance method registers existing object instances with a container-controlled lifetime [ContainerControlledLifetimeManager] it means that unity registers an object as a singleton instance.

By default lifetime for RegisterType method is TransientLifetimeManager, which creates new object of request type for each call.

Container.RegisterType<IProjectEngine, ProjectEngine>(); 

OR

Container.RegisterType<IProjectEngine, ProjectEngine>(new TransientLifetimeManager()); 
Unity Container have other lifetime managers so you can able to manage lifetime of created object differently.

Lifetime Manager
Description
TransientLifetimeManager
Unity Creates a new instance of request type for each call, when you call Resolve method
ContainerControlledLifetimeManager 
Unity creates a singleton object of request type on first call and it returns same object for subsequent Resolve call
HierarchicalLifetimeManager
Its same as ContainerControllerLifeTimeManager, only difference is that child and parent container creates its own singleton object and but both don’t share its singleton object
PerResolveLifetimeManager
It is same as TransientLifeTimeManager but it reuse same instanced object in the recursive object graph
PerThreadLifetimeManager
Unity Creates a singleton object per thread basis
ExternallyControlledLifetimeManager
It delegate to external source to manage the object and but for first resolve call, it creates object of requested type.

Thursday, July 6, 2017

Dependency Injection by Unity container

In this blog, we will discuss about the inversion of control (IoC) pattern and Dependency Injection and it will demonstrates how to implement dependency injection in ASP.NET Web API by using unity.

As Per Ioc Definition - a component should not depend directly upon any component rather it depends upon abstract

Dependency Injection is one way to implement of inversion of control (IoC) pattern and Dependency Injection makes component very loosely couple and loosely coupled application are easier to maintain and extend.

The Unity Container (Unity) is a lightweight, extensible dependency injection container. It facilitates building loosely coupled applications and provides developers with the following advantages:

      Simplified object creation, especially for hierarchical object structures and dependencies
      Abstraction of requirements; this allows developers to specify dependencies at run time or in configuration and simplify

Basically in dependency Injection process, the Unity Container is usually used to resolve the dependencies and injects through constructor or property and we register the type in container and retrieve the object related to type from constructor

Here is an example how to use the unity container in ASP.NET Web API to resolve the controller or business object dependency and inject dependency through constructor.

Here is a Web API Controller - TulipController which depends on business object – TulipBusiness, to get tulip sales data.

public class TulipController : ApiController
    {
        TulipBusiness _tulip;
        public TulipController()
        {
            tulip =new TulipBusiness();        
        }
        public decimal GetYearSales(int year)
        {
            return _tulip.GetTulipSales(year);
        }

    }


First we need to create an abstract type or interface of business object - TulipBusiness and then we need to inject this abstract type into object.

public interface ITulipBusiness
    {
        decimal GetYearSales(int year);     
    }

public class TulipBusiness : ITulipBusiness
    {
        public decimal GetYearSales(int year)
        {
        }
    }


I modified above Web API Controller, now Web API Controller depends on interface in place of a concrete class

public class TulipController : ApiController
    {
        ITulipBusiness _tulip;
        public TulipController(ITulipBusiness tulip)
        {
            _tulip = tulip;        
        }
        public decimal GetYearSales(int year)
        {
            return _tulip.GetTulipSales(year);
        }

    }

and we need to define the mapping of dependency type ITulipBusiness and its class TulipBusiness in unity Container class so whenever a dependency of type ITulipBusiness is required an instance of TulipBusiness is created and is injected into the dependent type by unit container.


public class UnityConfig
    {
        UnityContainer _container;
        public UnityContainer CurrentContainer { get { return _container; } }
        public UnityConfig()
        {
            _container = new UnityContainer();
            _container.RegisterType<ITulipBusinessTulipBusiness>();
        }

    }


Now whenever TulipController object will be created, Unity will be automatically resolved dependencies and inject object.

Here is an example how to manually resolve the dependency by Unity Container:
 
Simply call the Resolve method of unity container to create/instantiate the TulipController and its dependency TulipBusines object,

          var controller = _container.Resolve<TulipController>();

here before instantiate the tulipController object, unity container resolve all dependencies behind scenes and it first construct a TulipBusiness object and then passes it to thee constructor of the TulipController class.


In same way you can create instance of class which implemented specific Interface type by unit container.

var tulipBusiness = _container.Resolve<ITulipBusiness>();


There are other post related to dependency injection and unity container


Thanks for Visiting!!

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...