C# 依赖注入 Castle.Windsor

依赖注入工具 Castle.Windsor 的简单应用

Castle Windsor 是适用于.NET 的成熟的 IOC 容器

样例01

  1. 创建接口 IDependency1
namespace ConsoleApp2
{
    public interface IDependency1
    {
        object SomeObject { get; set; }
    }
}
  1. 创建接口 IDependency2
namespace ConsoleApp2
{
    public interface IDependency2
    {
        object SomeOtherObject { get; set; }
    }
}
  1. 实现接口 IDependency1
namespace ConsoleApp2
{
    public class Dependency1 : IDependency1
    {
        public object SomeObject { get; set; }
    }
}

  1. 实现接口 IDependency2
namespace ConsoleApp2
{
    public class Dependency2 : IDependency2
    {
        public object SomeOtherObject { get; set; }
    }
}
  1. 创建类 Main,构造函数注入
using System;

namespace ConsoleApp2
{
    public class Main
    {
        private IDependency1 object1;
        private IDependency2 object2;

        public Main(IDependency1 dependency1, IDependency2 dependency2)
        {
            object1 = dependency1;
            object2 = dependency2;
        }

        public void DoSomething()
        {
            object1.SomeObject = "Hello " + object1.GetType().ToString();
            Console.WriteLine(object1.SomeObject);
            object2.SomeOtherObject = "Hello " + object2.GetType().ToString();
            Console.WriteLine(object2.SomeOtherObject);
        }
    }
}

  1. 实现依赖注入
using Castle.Windsor;
using System;


namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建依赖注入容器,并且注入类和接口
            var container = new WindsorContainer();
            container.Register(Castle.MicroKernel.Registration.Component.For<Main>());
            container.Register(Castle.MicroKernel.Registration.Component.For<IDependency1>().ImplementedBy<Dependency1>());
            container.Register(Castle.MicroKernel.Registration.Component.For<IDependency2>().ImplementedBy<Dependency2>());

            //通过依赖注入容器解析类 `Main`,并调用方法
            var mainThing = container.Resolve<Main>();
            mainThing.DoSomething();
            Console.ReadKey();
        }
    }
}

结果
C# 依赖注入 Castle.Windsor_第1张图片

参考:https://github.com/castleproject/Windsor/blob/v4.0.0/docs/basic-tutorial.md

你可能感兴趣的:(C#实践)