Skip to content

Instantly share code, notes, and snippets.

@ruselknow
Created September 27, 2021 12:40
Show Gist options
  • Save ruselknow/cd2b823f936069628c862fc6fd9b5e08 to your computer and use it in GitHub Desktop.
Save ruselknow/cd2b823f936069628c862fc6fd9b5e08 to your computer and use it in GitHub Desktop.

Revisions

  1. ruselknow created this gist Sep 27, 2021.
    64 changes: 64 additions & 0 deletions SetterInjection.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    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 class MainClass
    {
    private IDependent _dependent;

    public void SetDependency(IDependent dependent)
    {
    _dependent = dependent
    ?? throw new ArgumentNullException(nameof(dependent), "Argument cannot be null");
    }

    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.SetDependency(dependency);

    mainClass.DoSomething();

    Console.ReadLine();
    }

    private static IDependent GetCorrectDependency()
    {
    return new Dependent1();
    }
    }
    }