Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
What is Inversion of Control
/*
This is worst case scenario
- You are unable to control the dependency or swap it for another without changing the NotUsingIoC source code.
- You are also going to have difficulties testing this as you cannot easily mock _someDependency.
*/
public class NotUsingIoC
{
private ISomeDependency _someDependency;
public NotUsingIoC()
{
_someDependency = new SomeDependency();
}
public void DoSomething()
{
_someDependency.MakeTheMagic();
}
}
/*
This is best case scenario
- The class expects to be passed an instance to satisfy ISomeDependency which means you have control over what to use.
- You can easily test this class by mocking the someDependency argument for the constructor.
- You have no dependency on any dependency injection framework within the class so it is not tying the class to a DI implementation or attributes.
*/
public class UsingIoC
{
private ISomeDependency _someDependency;
public NotUsingIoC(ISomeDependency someDependency)
{
_someDependency = someDependency;
}
public void DoSomething()
{
_someDependency.MakeTheMagic();
}
}
/*
This is a middle ground scenario
- The class can have the implementation for ISomeDependency changed externally which at least provides some flexibility
- You cannot easily test this as it depends upon a dependency injection/management container class which would need instantiating with correct dependencies.
- Your class is now tied to SomeDependencyManager, to use this class it MUST have the dependency logic setup, which makes it coupled in a bad way.
*/
using SomeDependencyContainer = SomeDependencyManager.Container;
public class UsingServiceLocation
{
private ISomeDependency _someDependency;
public UsingServiceLocation()
{
_someDependency = SomeDependencyContainer.Resolve<ISomeDependency>();
}
public void DoSomething()
{
_someDependency.MakeTheMagic();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.