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

Proxy Design Pattern in C#


Proxy design pattern is the example of Structural pattern. This design pattern is used to provide a proxy object which reference to other class object.

In proxy design pattern, there will be proxy class which represent the functionality of real class.

Now let’s see very basic example of proxy design pattern:

using System;

namespace ProxyDesign_Pattern_Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            ProxyClient obj = new ProxyClient();
            Console.WriteLine("Data from proxy={0}",obj.getData());
            Console.Read();
        }
    }

    public interface IClient
    {
        string getData();
    }

    public class RealClient : IClient
    {
        string msg;
        public RealClient()
        {
            Console.WriteLine("Real Client initialized ");
            msg = "My Test data";
        }
        public string getData()
        {
            return msg;
        }
    }

    public class ProxyClient : IClient
    {
        RealClient client = new RealClient();
        public ProxyClient()
        {
            Console.WriteLine("Proxy Client initialized");
        }
        public string getData() 
        {
          return  client.getData();
        }
    }
}

Explanation:

In the above example, we saw that we have created proxy class i.e ProxyClient and we are calling the original class method in proxy class. So this design pattern is called proxy design pattern.

Proxy_Design_Pattern

Factory pattern in C#


Note: If you are new to design pattern please look the part 1 of Design Pattern

https://chandradev819.wordpress.com/2015/12/17/what-is-the-design-pattern/

Factory pattern is creational design pattern in C#. As Factory name suggest that there should be something new create and construct.

In software architecture world factory pattern means centralize creation of object.

Now let take a scenario, we are working on some application and we got the scenario to generate the invoice on basis of City wise. Then generally we will write the two methods for generating the invoice and we will create the object with new keyword in UI layer.

Now we can optimize this code using factory design pattern. If we are using factory design pattern then no need create object in UI layer using New keyword. We can create factory class which will handle this task.

Now i am going to show extremely basic demo sample code for factory design pattern.

using System;

namespace factorypattern_example
{

    public class Program
    {
        public static void Main(string[] args)
        {
            Iinvoice objInvoice;
            Console.WriteLine("Enter the area Code");
            int invoiceType = Convert.ToInt32(Console.ReadLine());
            objInvoice = FactoryInvoive.GetInvoice(invoiceType);
            objInvoice.print();
            Console.ReadLine();
        }

    }

    /// <summary>
    /// Here we have created interface for common functionality
    /// </summary>
    public interface Iinvoice
    {
        void print();
    }

    /// <summary>
    /// Here we have implemented interface for bangalore branch
    /// </summary>
    public class ProductBangalore : Iinvoice
    {
        public void print()
        {
            //Note: this the demo code 
            Console.WriteLine("Invoice will be printed for Bangalore product");
        }
    }

    /// <summary>
    /// Here we have implemented interface for Mumbai branch 
    /// </summary>
    public class ProductMumbai : Iinvoice
    {
        public void print()
        {
            Console.WriteLine("Invoice will be printed for Mumbai product");
        }
    }

    /// <summary>
    /// Here we are creating the factory, which will take care of object creation task.
    /// </summary>
    public class FactoryInvoive
    {
        static public Iinvoice GetInvoice(int CityCode)
        {
            Iinvoice objInv;
            if(CityCode==100)
            {
                objInv = new ProductBangalore();

            }
           else if(CityCode==101)
            {
                objInv = new ProductMumbai();
            }
            else
            {
                return null;
            }
            return objInv;
        }
    }
}

Summary

If you observed in above code, in main method we are not creating object of class and factoryInvoice class has been created to handle the object creation task so this pattern is called as Factory Design Pattern.

What is the design pattern?


The design patterns are the recurring solution to recurring problem in Software architecture.
OR
Design pattern are the time tested practices for OOP problem. It is the process of solving object oriented programming language in much better ways.

There are 3 basic classification o design pattern

1. Creational patterns
2. Structural Patterns
3. Behavioral Pattern

Now let see some example of Creational Patterns example

1. Singleton Pattern
2. Abstract Factory Pattern
3. Factory Method pattern
4. Prototype Pattern
5. Builder Pattern

Singleton Pattern:

In this design pattern, we can create only one instance of Class. That instance needs to be accessible in different part of application. It can be use as global.
For example, we can use this pattern in so many scenarios like logging, Database access, and Holding Database Connection instance etc.

This pattern can be achieved by

1. Creating private construct of class.
2. Creating Instances and Method as static.

Now create the class like given below

namespace WebApplication2
{
    public class SingleTonTest
    {
        public static int intCounter;
 
        private SingleTonTest()
        {
        }
 
        public static void Hit()
        {
            intCounter++;
        }
 
        public static int getTotalHits()
        {
            return intCounter;
        }
    }
}

Step 2 Write the code in UI Layer like this

using System;
 
namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            HiCounter();
        }
 
        private void HiCounter()
        {
            SingleTonTest.Hit();
            Label1.Text = SingleTonTest.getTotalHits().ToString();
        }
 
        protected void Button2_Click(object sender, EventArgs e)
        {
            HiCounter();
        }
    }
}

Summary:

Here we learnt that how to use singleton design pattern in C#.