How to implement Structure Map in Asp.net MVC application?


Recently while working on one of client web based project, I got a chance to explore the structure map, so I have created small note on this topic

What is structure map ?

Structure map is the open source tool for creating the dependency in C#. As we know that using dependency injection we can create the loosely couple application. Which is one of the best practice for do architecture of any project.

There are so many open source tool available in community, but this is one of the famous IOC tool. Some of these are

Unity, Autofac, Ninject, StructureMap, etc

I have already written one post on Unity

https://chandradev819.wordpress.com/2018/06/05/how-to-implement-the-dependency-injection-in-asp-net-mvc/

In this small demo we are going to create simple MVC application where we will use this tool.
Step 1: Create the MVC application like this

Step 2: Add the structure map IOC by nuget package manager like this

You can also install the package manger using nuget console like this
PM> install-package StructureMap.MVC5

Step 3:
Structure Map tool will create the required file for application as given below image

Note: In the above all files the important file is DefaultRegistry we are going to configure the structuremap container

There are two approaches to configure the container

1. By using Auto registration (which will be there by default)
2. By using the explicit registration


Example for explicit registration

public DefaultRegistry()
{
Scan(
scan =>
{
scan.TheCallingAssembly();
//Approach 1
// scan.WithDefaultConventions();
scan.With(new ControllerConvention());
});

//Approach 2
For().Use();
}

Example for Auto registration

public DefaultRegistry()
{
Scan(
scan =>
{
scan.TheCallingAssembly();
//Approach 1
scan.WithDefaultConventions();
scan.With(new ControllerConvention());
});

//Approach 2
// For().Use();
}

Step 4: Create the Emp Model class in Models folder like this

namespace StructureMap_InMvc_Demo.Models.EmpRepo
{
    public class Emp
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }

    }

}

Step 5: Create the interface like this

using System.Collections.Generic;

namespace StructureMap_InMvc_Demo.Models.EmpRepo
{
    public interface IEmpRepository
    {
        IEnumerable<Emp> GetEmps();
    }
}

Step 6: Create the EmpRepository like this

using System.Collections.Generic;

namespace StructureMap_InMvc_Demo.Models.EmpRepo
{
    public class EmpRepository : IEmpRepository
    {
        public IEnumerable<Emp> GetEmps()
        {
            var empData = new List<Emp>()
            {
              new Emp{Id=1,EmpName="Chandradev", EmpAddress="Bangalore"},
              new Emp{Id=2,EmpName="Anvi", EmpAddress="Bangalore"},
              new Emp{Id=3,EmpName="Mohan", EmpAddress="Bangalore"}
            };
            return empData;
        }

    }
}

Step 7: Create the EmpController and write the code like this

using StructureMap_InMvc_Demo.Models.EmpRepo;
using System.Web.Mvc;

namespace StructureMap_InMvc_Demo.Controllers
{
    public class EmpController : Controller
    {
        private readonly IEmpRepository _empRepository;
        public EmpController(IEmpRepository empRepository)
        {
            _empRepository = empRepository;
        }
        // GET: Emp
        public ActionResult Index()
        {
            var emps = _empRepository.GetEmps();
            return View(emps);
        }
    }
}

Step 8: Create the view like this

@model IEnumerable<StructureMap_InMvc_Demo.Models.EmpRepo.Emp>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

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

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.EmpName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EmpAddress)
        </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>

Step 9: Run the application and navigate to emp controller, you will get out put like this