Simple example of dependency injection in C#

Look at the following code. We want to log messages in Employee class but we don’t want to be able to use different types of logging, i.e. we want to be able to easily switch classes that provide the logging.

The “trick” here is that we use the interface ILogger instead of a specific class name. Then, any class implementing the interface can be utilized. E.g.:

The output is then:

I.e. the object employee1 uses the LoggerOne class, while the object employee2 uses the LoggerTwo class.

Thanks to: http://www.codearsenal.net/2015/03/c-sharp-dependency-injection-simple.html