Property Injection 的一個簡單示例通過建構函式注入設定預設值

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();
        }
    }
}