Skip to content

Instantly share code, notes, and snippets.

@ritwickdey
Last active January 10, 2018 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritwickdey/b7ff5a61e4f07a246969f01440103d25 to your computer and use it in GitHub Desktop.
Save ritwickdey/b7ff5a61e4f07a246969f01440103d25 to your computer and use it in GitHub Desktop.
Example Of Dependency Injection in C#. (BTW, I'm not 100% sure :p )
namespace SomeNamespace
{
public interface ITest
{
void hello();
}
//NO Singleton Class, Simple One.
public class Test1 : ITest
{
public void hello()
{
System.Console.WriteLine("hiiiiiiii");
}
}
//This is Singleton Class, so this class has only one instance
public class Test2 : ITest
{
private static Test2 _instance;
public static Test2 Instance
{
get
{
if (_instance == null)
_instance = new Test2();
return _instance;
}
}
//Private constractor, so you can't create object of it from outsite of the class
private Test2() { }
public void hello()
{
System.Console.WriteLine("Heyyyyyyy");
}
}
/*`Demo` class is dependented on ITest*/
public class Demo
{
private readonly ITest _test;
//dependency of ITest
public Demo(ITest t)
{
_test = t;
}
public void foo()
{
//do work;
_test.hello();
}
}
public class MainClass
{
public static void Main()
{
Demo T1 = new Demo(new Test1()); //Depecency Injection
Demo T2 = new Demo(Test2.Instance); //Depecency Injection + Singleton (One single instance through out application life cycle)
T1.foo(); //hiiiiiiii
T2.foo(); //Heyyyyyyy
/*
Demo class is decoupled from Test1 & Test2 class.
Any class which is implemented `ITest` interface, can be injected into Demo class.
*/
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment