StructureMap IOC With ASP.NET MVC 5

Introduction

In this article, we will learn how we can implement StructureMap IOC container / dependency injection in ASP.NET MVC 5. Actually, we have different tools able to ensure inversion of control pattern, 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 application.

In this article, we are going to,

  • Create MVC application.
  • Configuring StructureMap IOC.
  • Create repository.
  • Create 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.

ASP.NET

Next, new dialog will pop up for selecting the template. We are going choose MVC template and click OK button.

ASP.NET

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 search box, then click on Install button, as shown below.

ASP.NET

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

PM> install-package StructureMap.MVC5

After installing StructureMap, from solution explorer we can notice that Dependency Resolution folder has been added, also StructuremapMVC.cs file in App_Start folder.

ASP.NET

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

DefaultRegistry.cs 

  1. namespace StructureMapMVC5.DependencyResolution {  
  2.     using Repository;  
  3.     using StructureMap.Configuration.DSL;  
  4.     using StructureMap.Graph;  
  5.   
  6.     public class DefaultRegistry : Registry {  
  7.         #region Constructors and Destructors  
  8.   
  9.         public DefaultRegistry() {  
  10.             Scan(  
  11.                 scan => {  
  12.                     scan.TheCallingAssembly();  
  13.                     scan.WithDefaultConventions();  
  14.                     scan.With(new ControllerConvention());  
  15.                 });  
  16.             For<ICustomerRepository>().Use<CustomerRepository>();  
  17.               
  18.         }  
  19.  
  20.         #endregion  
  21.     }  
  22. }   

In Default Registry class, we are going configure StructureMap container. In fact, we have two way to configure our container - by using explicit registrations or conventional auto registration.

As you can see, in this example we are composing our application object by connecting abstraction (in this case ICustomerRepository) to 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.

If you also have more repetitive similar registrations, such registrations are painful. StructureMap provides auto registration and conversion mechanism which is able to register types automatically. This means, 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

  1. using StructureMapMVC5.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace StructureMapMVC5.Repository  
  9. {  
  10.    public interface ICustomerRepository  
  11.     {  
  12.         IEnumerable<Customer> GetCustomers();  
  13.     }  
  14. }  
CustomerRepository.cs 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using StructureMapMVC5.Models;  
  6.   
  7. namespace StructureMapMVC5.Repository  
  8. {  
  9.     public class CustomerRepository : ICustomerRepository  
  10.     {  
  11.         public IEnumerable<Customer> GetCustomers()  
  12.         {  
  13.             var customerData = new List<Customer>()  
  14.             {  
  15.                new Customer() { ID = 1, Name = "Ali", Email = "[email protected]", Country = "Morocco"},  
  16.                new Customer() { ID = 2, Name = "Amine", Email = "[email protected]", Country = "Morocco"},  
  17.                new Customer() { ID = 3, Name = "Kumar", Email = "[email protected]", Country = "India"},  
  18.                new Customer() { ID = 4, Name = "Messi", Email = "[email protected]", Country = "Spain"},  
  19.             };  
  20.   
  21.             return customerData;  
  22.         }  
  23.     }  
  24. }   

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.

ASP.NET

Enter Controller name (‘CustomerController’).

ASP.NET

CustomerController.cs 

  1. using StructureMapMVC5.Models;  
  2. using StructureMapMVC5.Repository;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace StructureMapMVC5.Controllers  
  10. {  
  11.     public class CustomerController : Controller  
  12.     {  
  13.         private readonly ICustomerRepository _customerRepository;  
  14.   
  15.         public CustomerController(ICustomerRepository customerRepository)  
  16.         {  
  17.             _customerRepository = customerRepository;  
  18.         }  
  19.   
  20.         // GET: Customer  
  21.         public ActionResult Index()  
  22.         {  
  23.            var customers = _customerRepository.GetCustomers();  
  24.   
  25.             return View(customers);  
  26.         }  
  27.     }  
  28. }   

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

Adding View

It’s easy to do. Just right click on Index() action, select Add View and dialog will pop up; write a name for your View and finally, click Add.

ASP.NET 

  1. @model IEnumerable<StructureMapMVC5.Models.Customer>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. <p>  
  10.     @Html.ActionLink("Create New""Create")  
  11. </p>  
  12. <table class="table">  
  13.     <tr>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.Name)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.Email)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.Country)  
  22.         </th>  
  23.         <th></th>  
  24.     </tr>  
  25.   
  26. @foreach (var item in Model) {  
  27.     <tr>  
  28.         <td>  
  29.             @Html.DisplayFor(modelItem => item.Name)  
  30.         </td>  
  31.         <td>  
  32.             @Html.DisplayFor(modelItem => item.Email)  
  33.         </td>  
  34.         <td>  
  35.             @Html.DisplayFor(modelItem => item.Country)  
  36.         </td>  
  37.         <td>  
  38.             @Html.ActionLink("Edit""Edit"new { id=item.ID }) |  
  39.             @Html.ActionLink("Details""Details"new { id=item.ID }) |  
  40.             @Html.ActionLink("Delete""Delete"new { id=item.ID })  
  41.         </td>  
  42.     </tr>  
  43. }  
  44.   
  45. </table>   

Output

Now, you can run your application. Let’s see the output.

ASP.NET

Up Next
    Ebook Download
    View all
    Learn
    View all