Skip to content

Instantly share code, notes, and snippets.

@omidnasri
Forked from ardalis/Program.cs
Created May 27, 2016 18:43
Show Gist options
  • Save omidnasri/c64dfaa6ddd9f3c9dbc54b21e929ab4a to your computer and use it in GitHub Desktop.
Save omidnasri/c64dfaa6ddd9f3c9dbc54b21e929ab4a to your computer and use it in GitHub Desktop.
A StructureMap Example using a Console Application
using System;
using System.Linq;
using StructureMap;
namespace ConsoleApplication1
{
/// <summary>
/// See http://stackoverflow.com/questions/6777671/setting-up-structure-map-in-a-c-sharp-console-application
/// Updated for SM 4: http://ardalis.com/using-structuremap-4-in-a-console-app
/// </summary>
class Program
{
static void Main(string[] args)
{
// this is required to wire up your types - it should always happen when you app is starting up
InitIoC();
Console.WriteLine("StructureMap Initialized.");
// this takes advantage of the WithDefaultConventions() feature of StructureMap and will result in the Message type coming back.
IMessage myMessage = ObjectFactory.GetInstance<IMessage>();
Console.WriteLine(myMessage.Hello("Steve"));
// this uses the config.For<> syntax in the InitIoC() method
var myPerson = ObjectFactory.GetInstance<Person>(); // getting a Person will get all dependencies specified in its constructor
myPerson.Name = "Steve";
myPerson.Age = 38;
Console.WriteLine("Person:");
Console.WriteLine(myPerson);
Console.ReadLine();
}
private static void InitIoC()
{
ObjectFactory.Configure(config =>
{
config.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
// the last entry wins if there's more than one - generally it's a good idea to only have one mapping per type
config.For<IPersonFormatter>().Use<SimplePersonFormatter>();
config.For<IPersonFormatter>().Use<CapsPersonFormatter>();
});
}
}
public interface IMessage
{
string Hello(string person);
}
public class Message : IMessage
{
public string Hello(string person)
{
return String.Format("HELLO {0}!!!", person);
}
}
public interface IPersonFormatter
{
string Format(Person person);
}
public class Person
{
private readonly IPersonFormatter _personFormatter;
public Person(IPersonFormatter personFormatter)
{
_personFormatter = personFormatter;
}
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return _personFormatter.Format(this);
}
}
public class SimplePersonFormatter : IPersonFormatter
{
public string Format(Person person)
{
return String.Format("{0}, {1} years old.", person.Name, person.Age);
}
}
public class CapsPersonFormatter : IPersonFormatter
{
public string Format(Person person)
{
return String.Format("{0}, {1} years old.", person.Name, person.Age).ToUpper();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment