• 依赖注入 Castle.Windsor入门



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

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

    样例01

    1、创建接口 IDependency1

    namespace ConsoleApp2
    {
        public interface IDependency1
        {
            object SomeObject { get; set; }
        }
    }
    
      

    2、创建接口 IDependency2

    namespace ConsoleApp2
    {
        public interface IDependency2
        {
            object SomeOtherObject { get; set; }
        }
    }
    

    3、实现接口 IDependency1

    namespace ConsoleApp2
    {
        public class Dependency1 : IDependency1
        {
            public object SomeObject { get; set; }
        }
    }
    
    

    4、实现接口 IDependency2

    namespace ConsoleApp2
    {
        public class Dependency2 : IDependency2
        {
            public object SomeOtherObject { get; set; }
        }
    }
    
      

    5、创建类 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);
            }
        }
    }
    
    

    6、实现依赖注入

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

    结果
    在这里插入图片描述

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

  • 相关阅读:
    POJ 1129 深搜&四色染图&模拟
    POJ 1011 很经典的树枝拼凑的深度搜索
    HDU 2564 词组缩写
    Java中的split函数的用法
    java中next和nextline的区别
    简探this和super
    再探Java中的继承加载顺序
    Java面向接口编程小例子 2
    Dos命令整理集(持续更新)
    VMware WorkStation9.0虚拟机如何运行WINPE
  • 原文地址:https://www.cnblogs.com/springsnow/p/13850800.html
Copyright © 2020-2023  润新知