Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

StructureMap IOC With ASP.NET MVC 5

DZone's Guide to

StructureMap IOC With ASP.NET MVC 5

In this quick tutorial, we show you how to use several technologies together to create a web application we can use to perform StructureMap.

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Introduction

In this article, we will learn how we can implement a StructureMap IOC container/dependency injection in ASP.NET MVC 5. Actually, we have different tools which are able to ensure the inversion of control patterns like (Unity, Autofac, Ninject, StructureMap, etc…). In this demo, we will see the steps that should be used to perform StructureMap in ASP.NET MVC 5 applications.

In this article, we are going to:

  • Create an MVC application.
  • Configure the StructureMap IOC.
  • Create a repository.
  • Create a controller.

Create Your MVC Application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.

Image title

Next, a new window will pop up prompting you to select the template. We are going to choose the MVC template and click OK.

Image title

Configuring StructureMap IOC

After creating our project, we are going to add StructureMap IOC. For this, right click on References > Manage NuGet Packages, type StrucutreMap.MVC5 in the search box, then click on the install button as shown below.

Image title

You can also get StrcutureMap by using the package manager console and run the following command:

PM> install-package StructureMap.MVC5 

After installing StructureMap, from solution explorer we will notice that a Dependency Resolution folder has been added, as well as a  StructuremapMVC.cs file in our App_Start folder.

Image title

The important file which is needed is the DefaultRegistry.cs.

DefaultRegistry.cs

namespace StructureMapMVC5.DependencyResolution {
    using Repository;
    using StructureMap.Configuration.DSL;
    using StructureMap.Graph;

    public class DefaultRegistry : Registry {
        #region Constructors and Destructors

        public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
scan.With(new ControllerConvention());
                });
            For<ICustomerRepository>().Use<CustomerRepository>();

        }

        #endregion
    }

In the Default Registry class, we are going configure our StructureMap container. In fact, we have two ways of configuring our container: using explicit registrations or conventional auto registration.

As you can see, in this example, we are composing our application object by connecting an abstraction (in this case, ICustomerRepository) to a concrete type (represented by CustomerRepository). To do that, we are using the fluent API For<ICustomerRepository>().Use<CustomerRepository>() which registers a default instance for a given type.

Such registrations are painful. StructureMap provides auto registration and conversion mechanism which is able to register types automatically. This means that the scanner will register the default instance. Whenever you add an additional interface such IEmployeeRepository and a class EmployeeRepository, it’s automatically picked up by the scanner, scan.WithDefaultConventions();

Create Repository

ICustomerRepository.cs

using StructureMapMVC5.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StructureMapMVC5.Repository
{
   public interface ICustomerRepository
    {
        IEnumerable<Customer> GetCustomers();
    }
}

CustomerRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StructureMapMVC5.Models;

namespace StructureMapMVC5.Repository
{
    public class CustomerRepository : ICustomerRepository
    {
        public IEnumerable<Customer> GetCustomers()
        {
            var customerData = new List<Customer>()
            {
               new Customer() { ID = 1, Name = "Ali", Email = "Ali@gmail.com", Country = "Morocco"},
               new Customer() { ID = 2, Name = "Amine", Email = "Amine@gmail.com", Country = "Morocco"},
               new Customer() { ID = 3, Name = "Kumar", Email = "Kumar@gmail.com", Country = "India"},
               new Customer() { ID = 4, Name = "Messi", Email = "Messi@gmail.com", Country = "Spain"},
            };

            return customerData;
        }
    }
}

Create a Controller

Now, we are going to create a controller. Right click on the controllers folder > Add > Controller> selecting MVC5 Controller – Empty > click Add.

Image title

Enter the Controller name (‘CustomerController’).

Image title

CustomerController.cs

using StructureMapMVC5.Models;
using StructureMapMVC5.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace StructureMapMVC5.Controllers
{
    public class CustomerController : Controller
    {
        private readonly ICustomerRepository _customerRepository;

        public CustomerController(ICustomerRepository customerRepository)
        {
            _customerRepository = customerRepository;
        }

        // GET: Customer
        public ActionResult Index()
        {
           var customers = _customerRepository.GetCustomers();

            return View(customers);
        }
    }
}

As you can see, I am creating the Index() action that returns a customers list from the GetCustomers() method.

Adding View

It’s easy to do. Just right click on the Index() action, select Add View, and a window will pop up. Write a name for your view, and click Add.

Image title

@model IEnumerable<StructureMapMVC5.Models.Customer>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Country)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Country)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

Output

Now you can run your application and see the output.       

Image title  

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
ioc containers ,dependecy injection ,asp.net mvc5 ,web dev

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}