August 16, 2016

Dependency Injection

Got nice example from below link
http://www.codearsenal.net/
http://www.codearsenal.net/2015/03/c-sharp-dependency-injection-simple.html#.V7L1TPl97IU

let's say Employee, and two or more different loggers for that class. 
Each logger prints messages in his own particular way and you want to have control of which logger to use for Employee during its instantiation.

class Program
    {
        static void Main(string[] args)
        {

            Employee employee1 = new Employee(new LoggerOne());
            Employee employee2 = new Employee(new LoggerTwo());
            Console.ReadKey();
        }
    }

    public class Employee
    {
        public Employee(ILogger logger)
        {
            logger.WriteToLog("New employee created");
        }
    }

    public interface ILogger
    {
        void WriteToLog(string text);
    }

    public class LoggerOne : ILogger
    {
        public void WriteToLog(string text)
        {
            Console.WriteLine(text);
        }
    }

    public class LoggerTwo : ILogger
    {
        public void WriteToLog(string text)
        {
            Console.WriteLine("***********\n {0}\n***********", text);
        }
    }

And the output: 
New employee created

*******************
New employee created
*******************

No comments: