Wednesday, 18 February 2015

DI - ASP.NET MVC 4 using Unity

In my previous post I have already Described about DI and IOC [Click here]. Here in this Post I'll Describe How to Implement DI using Unity Container in  MVC4.

As you know, in MVC, Controller depends on Model for data processing or you can say for executing business logic. This article will explain you how can you decouple model layers from the controller layer in an ASP.NET MVC application using Unit DI Container.

Step 1- First step is to create a new Asp.Net MVC4 Project.

Step 2- Install Unity Container
Now install Unity.Mvc4 Container using NuGet Package Manager Console tool as shown below:


You can also do online search for Unity.Mvc4 Container by navigating to Tools=>Extension and Update..=>Online options in Visual Studio 2012 or 2010SP1 and install it.

When it will be installed successfully, you will be find the following two references add to your project and a Bootstrapper.cs class file at project level, as shown below:



  public static class Bootstrapper
  {
    public static IUnityContainer Initialise()
    {
      var container = BuildUnityContainer();

      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      return container;
    }

    private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

      // register all your components with the container here
      // it is NOT necessary to register your controllers

      // e.g. container.RegisterType<ITestService, TestService>(); 
      RegisterTypes(container);

      return container;
    }

    public static void RegisterTypes(IUnityContainer container)
    {
   
    }
  }

Step 3- For demonstrating dependency injection we need some sort of interfaces and their concrete implementations, so in that regard I will add a new interface named IMessageService and it’s
implementation MessageService in the Model folder to the project root.

Here is the interface IMessageService:

    public interface IMessageService
    {
        string GetMessage();
    }

and MessageService:
  public class MessageService :IMessageService
    {
        public string GetMessage()
        {
           return "Hello World!";
        }

    }
Step 4- Register the Dependency in Bootstrapper.cs file
Replace BuildUnityContainer method's content with the following code that registers the MessageService Service. You can also register the HomeController in which we will inject the dependency, but it is optional.

    private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

      // register all your components with the container here
      // it is NOT necessary to register your controllers

      // e.g. container.RegisterType<ITestService, TestService>(); 
      container.RegisterType<IMessageService, MessageService>();
      RegisterTypes(container);

      return container;

    }

Step 5- Inject Service to Controller
Now inject the dependency for the IMessageService interface using the HomeController's constructor as shown below:

   public class HomeController : Controller
    {
        private readonly IMessageService _messageService;
        public HomeController(IMessageService messageservice)
        {
            this._messageService = messageservice;
        }

        public ActionResult Index()
        {
            ViewBag.Message = _messageService.GetMessage();

            return View();
        }
    }

Index.cshtml
<h2>@ViewBag.Message</h2>

Step 6 – Setup Dependency Injection with Unity in Global.asax.cs
Now, setup the Bootstrapper class with in the Application_Start method so that it can initialize all dependencies. This will be done by calling Initialise() method of the Bootstrapper class as shown below:

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            //Setup DI
            Bootstrapper.Initialise();
        }

Step 7- Run the Application and see how it works.


It's all Done.

I hope you enjoyed with DI.

Download the Complete Project here Click me -
Continue Reading →

Sunday, 15 February 2015

DI - ASP.NET MVC 4 using Ninject

Dependency Injection is an implementation of the Inversion of Control pattern.  There are two possible implementations for IoC:
  1. Service Locator
  2. Dependency Injection
I've already discussed about What is DI and How to Use it Click here to Read about DI . here, in this Post I am Going to Use DI using NInject Container.
There are lots of IoC containers available:
  1. Unity
  2. CastleWindsor
  3. StructureMap
  4. Spring.NET
  5. Ninject
  6. Autofac 
At runtime, they take care of the responsibility of passing in the correct type. Many of them are open source or freely available.

NInject- Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test, and modify.

Let’s start

Create a new Mvc 4 Project.
Add NInject from Manage Nuget Package Reference.

For demonstrating dependency injection we need some sort of interfaces and their concrete implementations, so in that regard I will add a new interface named IMessageService and it’s
implementation MessageService in the Model folder to the project root.
Here is the interface IMessageService:

    public interface IMessageService
    {
        string GetMessage();
    }

and MessageService:

  public class MessageService :IMessageService
    {
        public string GetMessage()
        {
           return "Hello India Won the Match.";
        }

    }

Add a new class in Model name NInjectDependencyResolver that implements IDependencyResolver Interface and Implements it's two functions object GetService(Type serviceType) and IEnumerable<object> GetServices(Type serviceType) for DI work, so It can be implement like this:

using Ninject;
using Ninject.Syntax;
    public class NInjectDependencyResolver : IDependencyResolver
    {
        private readonly IResolutionRoot _resolutionRoot;

        public NInjectDependencyResolver(IResolutionRoot kernel)
        {
            _resolutionRoot = kernel;
        }

        public object GetService(Type serviceType)
        {
            return _resolutionRoot.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _resolutionRoot.GetAll(serviceType);
        }

        public static void setUpDependencyInjection()
        {
            //Create NInject DI Kernel
            IKernel kernel = new StandardKernel();

            //Register Services with NInject DI Container
            kernel.Bind<IMessageService>().To<MessageService>();

            //Tell ASP.Net MVC to use our NInject DI COntainer
            DependencyResolver.SetResolver(new NInjectDependencyResolver(kernel));
        }
    }

ok, in the method above setUpDependencyInjection() I created a standard kernel which is implemented in the Ninject.dll and bind our service to it’s concrete implementation, say whenever the application encounters the IMessageService then it will automatically creates a new instance of MessageService damn simple isn’t it, don’t forget to call above method in Application_Start().

Now in the Application_Start(),  hook DI related stuff. Call setUpDependencyInjection function in Application_Start() Function.

        protected void Application_Start()
        {
          ......
          ...

           NInjectDependencyResolver.setUpDependencyInjection();
        }

To test it, open up HomeController and change it like that:

    public class HomeController : Controller
    {
        private readonly IMessageService _messageService;
        public HomeController(IMessageService messageservice)
        {
            this._messageService = messageservice;
        }

        public ActionResult Index()
        {
            ViewBag.Message = _messageService.GetMessage();
            return View();
        }
    }

First, I add a private readonly field _messageService that holds our service instance on the fly. I also add a class constructor which takes single parameter of type IMessageService and then set it to our private field.
In Index() ActionResult method I called the GetMessage() and we are done, look I didn’t create a new instance of MessageService class anywhere it will automatically created by our DI container.

Index.cshtml
<h2>@ViewBag.Message</h2>

Now Run the Application and see the output :


you see the message above it comes from our MessageService class’s GetMessage() method which I called in HomeController.

The advantages of using Dependency Injection pattern and Inversion of Control are the following:

  1. Reduces class coupling
  2. Increases code reusing
  3. Improves code maintainability
  4. Improves application testing
Hope you understand how DI works in ASP.NET MVC 4 with Ninject.

Download the Complete Project here Click me -
Read More about NInject on Codeplex Click me -
Continue Reading →

Thursday, 12 February 2015

C# Program - to Check Number is Even or Odd

This C# Program checks if a given integer is Odd or Even. Here if a given number is divisible by 2 with the remainder 0 then the number is an Even number. If the number is not divisible by 2 then that number will be an Odd number.

   class Program
        {
            static void Main(string[] args)
            {
                int i;
                Console.Write("Enter a Number : ");
                i = int.Parse(Console.ReadLine());
                if (i % 2 == 0)
                {
                    Console.Write("Entered Number is an Even Number");
                    Console.Read();
                }
                else
                {
                    Console.Write("Entered Number is an Odd Number");
                    Console.Read();
                }
            }

        }
Continue Reading →

C# Program - to Check Leap Year or Not

This C# Program Checks Whether the Entered Year is a Leap Year or Not.When A year is divided by 4. If remainder becomes 0 then the year is called a leap year..

namespace Program
    {
        class leapyear
        {
            static void Main(string[] args)
            {
                leapyear obj = new leapyear();
                obj.readdata();
                obj.leap();
            }
            int y;
            public void readdata()
            {
                Console.WriteLine("Enter the Year in Four Digits : ");
                y = Convert.ToInt32(Console.ReadLine());
            }
            public void leap()
            {
                if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))
                {
                    Console.WriteLine("{0} is a Leap Year", y);
                }
                else
                {
                    Console.WriteLine("{0} is not a Leap Year", y);
                }
                Console.ReadLine();
            }
        }

     }
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives