-
Notifications
You must be signed in to change notification settings - Fork 16
ikopylov edited this page Jan 15, 2016
·
6 revisions
IoC (inversion of control) is the pattern where you can substitute the particular implementation of interface or abstract class at runtime (for example, by passing the concrete instance to the constructor).
To follow this pattern the library provides an IoC container. It maintain the collection of associations between abstract type and it's concrete implementation. This associations are added on the start-up and later used to inject this implementations to the constructor of your class.
Sample code:
public interface ITestInterface
{
void DoWork();
}
public class TestImplementation: ITestInterface
{
public void DoWork() { }
}
public class TestInjectionToConstructor
{
public TestInjectionToConstructor(int intVal, string stringVal, double doubleVal, ITestInterface worker)
{
Console.WriteLine(intVal);
Console.WriteLine(stringVal);
Console.WriteLine(doubleVal);
Console.WriteLine(worker.GetType().Name);
}
}
static void Main()
{
// Create container
var container = new TurboContainer();
// singleton for int
container.AddSingleton<int>(10);
// value for string
container.AddSingleton<string>("value");
// ITestInterface resolved in PerCall way (per Thread is also supported)
container.AddPerCall<ITestInterface, TestImplementation>();
// Add association with resolving by delegate
container.AddAssociation<double>(new PerCallLifetime(typeof(double), r => 15.0));
// ourStr == "value"
var ourStr = container.Resolve<string>();
// ourWorker is a new instance of type TestImplementation
var ourWorker = container.Resolve<ITestInterface>();
// we can create any object and inject values to constructor
var obj = container.CreateObject<TestInjectionToConstructor>();
// Dispose container
container.Dispose();
}