Skip to content

Instantly share code, notes, and snippets.

@ruselknow
Created September 27, 2021 13:34
Show Gist options
  • Select an option

  • Save ruselknow/040fb99ee1b79a21115b297b04fa56c0 to your computer and use it in GitHub Desktop.

Select an option

Save ruselknow/040fb99ee1b79a21115b297b04fa56c0 to your computer and use it in GitHub Desktop.
Interface Injection
using System;
namespace DependencyInjection
{
public interface IDependent
{
void DoSomething();
}
public class Dependent1 : IDependent
{
public void DoSomething()
{
Console.WriteLine("Hello from Dependent1");
}
}
public class Dependent2 : IDependent
{
public void DoSomething()
{
Console.WriteLine("Hello from Dependent2");
}
}
public interface IInjectDependent
{
void InjectDependent(IDependent dependent);
}
public class MainClass : IInjectDependent
{
private IDependent _dependent;
public void InjectDependent(IDependent dependent)
{
_dependent = dependent;
}
public void DoSomething()
{
_dependent.DoSomething();
}
}
internal static class Program
{
private static void Main()
{
// Get the correct dependency
var dependency = GetCorrectDependency();
// Create class
var mainClass = new MainClass();
//Inject the dependency
mainClass.InjectDependent(dependency);
mainClass.DoSomething();
Console.ReadLine();
}
private static IDependent GetCorrectDependency()
{
return new Dependent1();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment