Dependency Injection in .NET with examples?
Can someone explain dependency injection with a basic .NET example and provide a few links to .NET resources to extend on the subject?
This is not a duplicate of What is dependency injection? because I am asking about specific .NET examples and resources.
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:
- Abstract the interface of CardPresenceChecker by creating Interface ICardPresenceChecker;
- Make explicit that this CardPresenceChecker only works for the library of Company X, by changing its name to XCardPresenceChecker ;
- Have XCardPresenceChecker implement Interface ICardPresenceChecker ;
- Abstract the property of LogInService to be of type ICardPresenceChecker instead of ‘knowing’ exactly which implementation is held aboard;
- And last but not least, demand from users (other developers) of LogInService that they provide any class that at least implements ICardPresenceChecker so that LogInService can do its thing.
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());"