dependency-injection A Simple Example of Property Injection, setting the default via constructor injection


Example

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var dep = new DefaultDependency();
            var foo = new ClassWithDependency(dep);

            foo.DoSomething();

            var bar = new InjectedDependency();

            foo.Dependency = bar; //Injecting the dependency via a property

            foo.DoSomething();

            Console.ReadLine();
        }

    }

    public interface IDependency
    {
        void DoSomething();
    }

    public class DefaultDependency: IDependency
    {
        public void DoSomething()
        {
            Console.WriteLine("Default behaviour");
        }
    }

    public class InjectedDependency: IDependency
    {
        public void DoSomething()
        {
            Console.WriteLine("Different behaviour");
        }
    }

    public class ClassWithDependency
    {
        public ClassWithDependency(IDependency dependency)
        {
            Dependency = dependency;
        }

        public IDependency Dependency { get; set; }

        public void DoSomething()
        {
            Dependency.DoSomething();
        }
    }
}