Skip to content

Dependency Injection

Xet Erixon edited this page Jun 28, 2017 · 5 revisions

The basics

Say we have a class implementing an interface and another class depending on an implementation of that interface.

using NotNet.Core;
public interface ITest{}

public class Test1 : ITest{}

public class Test2
{
	private ITest _test;

	public Test2(ITest test){
		_test = test;
	}
}

Normally you will do something like this

public static void Main(string[] args)
{
	var t2 = new Test2(new Test1());
}

Nothing wrong with that, but you get a fairly hard coupling between Test2 and Test1.

Enter the dependency injector:

public static void Main(string[] args)
{
	// Register the resolvable stuff
	Container.Default.RegisterTransient<ITest,Test1>();
	Container.Default.RegisterTransient<Test2>();
	
	// Create an instance of Test2. The constructor argument will 
	// be resolved and injected
	var t2 = Container.Default.Resolve<Test2>();
	
}

So how is this better? It's way more code than the first example...

Ok, so say you do var t = new Test2(new Test1()); 200 times in you large app. Unlikely perhaps, but bare with me... Say now that you find and want to use a better implementation of ITest, the extremely well oiled class Test3. In that case you got to do a search for the usage of Test1 and replace it with Test3.

Using the service locator, you only got to do Container.Default.RegisterTransient<ITest,Test3>(); and you're set..

It's possible to pass "non-resolvable" objects to the constructor as well. Container.Default.Resolve<ISomeInterface>(arg);

Restriction: The "non-resolvable" object(s) must be the last arguments in the constructor. Resolvable objects are injected first.

Notes

  • The container itself is resolvable as IContainer (it's not possible to roll your own container yet)

More

Have a look in the test-project for more examples

Clone this wiki locally