Tuesday, May 20, 2014

StructureMap is one of good dependency Injection Tool which provide loose coupling between a dependent class and a set of concrete classes. It also Provide best Unit Test using mocking.It has lot of flexibility when are using mvc with razor engine.

download the project

https://sourceforge.net/projects/structuremapdemobyrajesh/


1) StructureMap provides a facility to enable loose coupling between classes and their dependencies.
2) StructureMap can greatly enhance the opportunities for code reuse by minimizing direct coupling between classes and configuration mechanisms.
3) If your are using IOC then you can do better unit testing using moq.


Here  I  am just giving simple example which is used in c# only not used in mvc.




using StructureMap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StructureMapDemo
{


    public interface IPoltics
    {

         string TeamWinner(Party party);
         int NoOfParticapteInLokshava(int seat);
    }

    public class Party
    {
        public string Name { get; set; }
        public int TotalSeat { get; set; }
    }

    public class Poltics : IPoltics
    {

     
        public string TeamWinner(Party party)
        {

            return string.Format("My PartyName is {0}",party.Name);

        }

        public int NoOfParticapteInLokshava(int seat)
        {
            return seat;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            //First Intialize the structure map
            Console.WriteLine("StructureMap Initialized.");
            //In structure map, There are  many way to register the services and ObjectFactor.Intialize is one of them.
            IntializeIoC();        

            // this takes advantage of the WithDefaultConventions() feature of StructureMap and will result in the Message type coming back.
            IPoltics myPoltics = ObjectFactory.GetInstance<IPoltics>();

            var myParty = ObjectFactory.GetInstance<Party>();
            myParty.Name = "BJP";
            myParty.TotalSeat = 278;
            Console.WriteLine("Result for 2014 Lok Sabha :");
            Console.WriteLine(myParty);

            Console.ReadLine();
            myPoltics.TeamWinner(myParty);
         
        }

        private static void IntializeIoC()
        {
            ObjectFactory.Configure(config =>
            {
                config.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                });


                config.For<IPoltics>().Use<Poltics>();
             

            });
        }
    }
}

5 comments: