Last Updated: February 25, 2016
·
375
· rajesh_kashyap

How to Use dependecy Injection using StructureMap

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

namespace StructureMapDemo
{

public interface IPoltics
{

    public string TeamWinner(Party party);
    public 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>();


        });
    }
}

}