Using dependency injection, we can pass an instance of class C to class B, and pass an instance of B to class A, instead of having these classes to construct the instances of B and C. In the example, below, class Runner has a dependency on the class Logger.
Dependency injection in . NET is a built-in part of the framework, along with configuration, logging, and the options pattern. A dependency is an object that another object depends on. Examine the following MessageWriter class with a Write method that other classes depend on: C# Copy.
The intent of Dependency Injection is to make code maintainable. Dependency Injection helps to reduce the tight coupling among software components. Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.
The Dependency Injection pattern is a particular implementation of Inversion of Control. Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).
Here's a common example. You need to log in your application. But, at design time, you're not sure if the client wants to log to a database, files, or the event log.
So, you want to use DI to defer that choice to one that can be configured by the client.
This is some pseudocode (roughly based on Unity):
You create a logging interface:
public interface ILog
{
void Log(string text);
}
then use this interface in your classes
public class SomeClass
{
[Dependency]
public ILog Log {get;set;}
}
inject those dependencies at runtime
public class SomeClassFactory
{
public SomeClass Create()
{
var result = new SomeClass();
DependencyInjector.Inject(result);
return result;
}
}
and the instance is configured in app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name ="unity"
type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity>
<typeAliases>
<typeAlias alias="singleton"
type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" />
</typeAliases>
<containers>
<container>
<types>
<type type="MyAssembly.ILog,MyAssembly"
mapTo="MyImplementations.SqlLog, MyImplementations">
<lifetime type="singleton"/>
</type>
</types>
</container>
</containers>
</unity>
</configuration>
Now if you want to change the type of logger, you just go into the configuration and specify another type.
Ninject must have one of the coolest sample out there: (pieced from the sample)
interface IWeapon {
void Hit(string target);
}
class Sword : IWeapon {
public void Hit(string target) {
Console.WriteLine("Chopped {0} clean in half", target);
}
}
class Shuriken : IWeapon {
public void Hit(string target) {
Console.WriteLine("Shuriken tossed on {0}", target);
}
}
class Samurai {
private IWeapon _weapon;
[Inject]
public Samurai(IWeapon weapon) {
_weapon = weapon;
}
public void Attack(string target) {
_weapon.Hit(target);
}
}
class WeaponsModule: NinjectModule {
private readonly bool _useMeleeWeapons;
public WeaponsModule(bool useMeleeWeapons) {
_useMeleeWeapons = useMeleeWeapons;
}
public void Load() {
if (useMeleeWeapons)
Bind<IWeapon>().To<Sword>();
else
Bind<IWeapon>().To<Shuriken>();
}
}
class Program {
public static void Main() {
bool useMeleeWeapons = false;
IKernel kernel = new StandardKernel(new WeaponsModule(useMeleeWeapons));
Samurai warrior = kernel.Get<Samurai>();
warrior.Attack("the evildoers");
}
}
This, to me, reads very fluently, before you start up your dojo you can decide how to arm your Samurais.
I think it is important that you first learn DI without IoC Containers. So therefor I've written an example that slowly builts up to an IoC Container. It's a real example from my work, but still made basic enough for novices to grab the essence of DI. You can find it here: https://dannyvanderkraan.wordpress.com/2015/06/15/real-world-example-of-dependeny-injection/
It's in C#.NET and later on it uses Unity.
Update after comment:
Relevant section of article
"Observe the following changes to the original design:
We went for the “Constructor Injection” pattern to implement DI and the refactoring steps were:
LogInService’s constructor looks like:
this.myCardPresenceChecker = cardPresenceChecker;
this.myCardPresenceChecker.CardIn += MyCardPresenceChecker_CardIn;
this.myCardPresenceChecker.CardOut += MyCardPresenceChecker_CardOut;
this.myCardPresenceChecker.Init();
So where do you provide LogInService with an implementation of ICardPresenceChecker? You usually want this ‘mapping’ (in this example we would ‘map’ ICardPresenceChecker to XCardPresenceChecker) at one central place at the startup of an application, known conceptually as the “Composition Root”. For an ol’ regular Console Application that could be the void Main in the Program class. So for this example, this piece of code would be used at the aformentioned place:
LogInService logInService = new LogInService(new XCardPresenceChecker());"
I've got Dependency Injection with a really simple example like this.
See the class below, you'll get the whole idea. As you see unless you supply file it will use the default one settings file, but you can set a settings file and then the class will use it.
Public Class ProcessFile
Private _SettingsFile As String = "settings.bin"
Public Sub New()
End Sub
Public Sub New(settings As String)
_SettingsFile= settings
End Sub
Public Function ReadFile() As String
'Do stuff based on the settings stored in the _SettingsFile
End Function
End Class
Obviously this is the most basic case. In real world you can do the same thing with class types, such as you've got Database Layer and you can switch the underlying database dll by doing dependency injection and you code will work with any database as soon as you can provide the valid class (a class which implements the interface you are using).
After got the basic you can do this on larger scope and totally independent from the application by using DI frameworks like unity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With