Last active
December 21, 2015 03:18
-
-
Save mat-mcloughlin/6240821 to your computer and use it in GitHub Desktop.
A very basic example of an IoC Container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var container = new Container(); | |
container.Bind<ICar, Car>(); | |
container.Bind<IEngine, Engine>(); | |
container.Bind<IStarterMotor, StarterMotor>(); | |
var car = container.Resolve<ICar>(); | |
car.StartEngine(); | |
Console.ReadLine(); | |
} | |
} | |
class Car : ICar | |
{ | |
public Car(IEngine engine) | |
{ | |
Console.WriteLine("Car Created!"); | |
} | |
public void StartEngine() | |
{ | |
Console.WriteLine("-- Engine Started --"); | |
} | |
} | |
class Engine : IEngine | |
{ | |
public Engine(IStarterMotor startMotor) | |
{ | |
Console.WriteLine("Engine Created!"); | |
} | |
} | |
class StarterMotor : IStarterMotor | |
{ | |
public StarterMotor() | |
{ | |
Console.WriteLine("Starter Motor Created!"); | |
} | |
} | |
internal interface ICar { void StartEngine();} | |
internal interface IStarterMotor { } | |
internal interface IEngine { } | |
/// <summary> | |
/// IoC Container | |
/// </summary> | |
class Container | |
{ | |
private readonly Dictionary<Type, Func<object>> _providers; | |
public Container() | |
{ | |
_providers = new Dictionary<Type, Func<object>>(); | |
} | |
public void Bind<TInterface, TConcrete>() where TConcrete : TInterface | |
{ | |
_providers[typeof(TInterface)] = () => Resolve(typeof(TConcrete)); | |
} | |
public T Resolve<T>() | |
{ | |
return (T)_providers[typeof(T)](); | |
} | |
private object Resolve(Type type) | |
{ | |
var constructor = type.GetConstructors().SingleOrDefault(); | |
var parametersInfo = constructor.GetParameters(); | |
var parameters = new List<object>(); | |
foreach (var parameterInfo in parametersInfo) | |
{ | |
parameters.Add(_providers[parameterInfo.ParameterType]()); | |
} | |
return constructor.Invoke(parameters.ToArray()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment