Click here to Skip to main content
15,887,596 members
Articles / Web Development / HTML
Tip/Trick

ASP.NET MVC Dependency Injection using Windsor

Rate me:
Please Sign up or sign in to vote.
4.46/5 (6 votes)
9 Nov 2015CPOL2 min read 31.3K   593   12   3
Extend ASP.NET MVC behavior to auto wire controller dependency

Introduction

In this tip, I will demonstrate how to extend ASP.NET MVC Behaviour using Windsor as Dependency Injection/Inversion of Control container. Windsor is one of many libraries used for Dependency Injection. It's easy to setup and use.

If you don't know what Dependency Injection (DI) is, you can read the article about DI here.

Create ASP.NET MVC Application

To create ASP.NET MVC application, select ASP.NET Web application in project template and name the application WindsorMvcDemo. Click OK to create the application.

Image 1

Add Windsor Library Reference

The easiest way to reference windsor library is using Nuget package installer. Right click on Reference, and select Manage Nuget Package.

Image 2

In the manage nuget package dialog, type windsore mvc in search textbox, then select Castle Windsor MVC Bootstrapper in the list, and click Install. It will download the lib and its dependency automatically.

Image 3

After installation complete, it generated 4 files:

  1. App_Start\ContainerBootstrapper.cs
  2. App_Start\WindsorActivator.cs
  3. Plumbing\WindsorControllerFactory.cs
  4. Installers\ControllersInstaller.cs

The first 3 files are used by the Windsor library to configure the controller. Don't worry, you don't need to touch those files. The 4th file is where the controller behaviour is extended by the lib. You will configure your interface and implementation class in the Installer folder. Before that, we need to create our interface and implementation class.

Create Interface and Implementation Class

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WindsorMvcDemo.Models
{
    public class ToDo
    {
        public string Title { get; set; }
        public DateTime Date { get; set; }
        public string Comment { get; set; }
    }

    public interface ToDoListService
    {
        IEnumerable<ToDo> GetToDoList();
    }

    public class ToDoListServiceImpl : ToDoListService
    {
        public IEnumerable<ToDo> GetToDoList()
        {
            return new List<ToDo>
            {
                new ToDo
                {
                    Title = "Meeting with client",
                    Comment = "Meet at the office on 08:00AM",
                    Date = DateTime.Today
                },
                new ToDo
                {
                    Title = "Lunch with Girlfriend",
                    Comment = "At restaurant near the office",
                    Date = DateTime.Today
                },
                new ToDo
                {
                    Title = "Go to dentist",
                    Comment = "Scheduled Visit to dentist",
                    Date = DateTime.Today.AddDays(2)
                }
            };
        }
    }
}

Create ToDoListController

For demonstation, let's create a Controller that will show list of ToDo.

C#
public class ToDoListController : Controller
{
    private ToDoListService toDoListService;

    public ToDoListController(ToDoListService service)
    {
        this.toDoListService = service;
    }

    // GET: ToDoList
    public ActionResult Index()
    {
        var model = toDoListService.GetToDoList();

        return View(model);
    }
}

Configure the Dependency

In the ToDoListController above, notice the constructor. The constructor requires ToDoListService parameter. How can we pass that parameter while we cannot instantiate the controller class? That's where the Windsor library plays the role. We must first configure the dependency by registering the interface and service class to Windsor Container. Create a class that implement IWindsorInstaller interface. When application starts, Windsor will search all classes that implement the interface, instantiate the class and call Install method.

Below is how to register the interface and implementation:

C#
public class ServiceInstaller : IWindsorInstaller
{
    public void Install(Castle.Windsor.IWindsorContainer container,
	Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {
        container.Register(
            Component
                .For<ToDoListService>()
                .ImplementedBy<todolistserviceimpl>()
                .LifestyleTransient());
        }
    }
}

Create ToDo List View

Next, create a view that will list the todo list. Open ToDoListController, right click on Index method, select Add View. In Add View dialog, select List in Template options, and select ToDo model in Model class. Leave the Data Context class blank and then click OK to create the View. MVC framework will scaffold the view and generate Index.cshtml in Views\ToDoList folder.

In this demo, we only need to show the list of todo, so remove the Edit, Detail and Delete link generated by MVC framework.

The Index.cshtml should be like below:

Image 4

Create ToDo List View

To run the application, press F5 and navigate to http://localhost:port/ToDoList in browser address. It should show list of todo as below:

Image 5

Conclusion

That is how we use Windsor to extend ASP.NET MVC behaviour to auto wire the controller depedency using Windsor container as the Dependency Injection. For more details about Windsor, please go here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer MITRAIS
Indonesia Indonesia
I have been working in software development using Microsoft technologies for many years.

Comments and Discussions

 
QuestionError- No parameterless constructor defined for this object. Pin
nambir6-Feb-18 3:20
nambir6-Feb-18 3:20 
GeneralMy vote of 5 Pin
Santhakumar M10-Nov-15 22:21
professionalSanthakumar M10-Nov-15 22:21 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun9-Nov-15 18:57
Humayun Kabir Mamun9-Nov-15 18:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.