C# Unity 依赖注入学习

参考博客:Unity依赖注入使用详解

一、创建项目,从NuGet控制台安装Unity。

C# Unity 依赖注入学习_第1张图片C# Unity 依赖注入学习_第2张图片

二、新建接口IFly,ICanFly

namespace UnityDemo
{
    public interface IFly
    {
        void Fly();
    }
}
namespace UnityDemo
{
    public interface ICanFly
    {
        void FlyToSpace();
    }
}

三、新建实现类WingFly,MachibeFly实现IFly接口

namespace UnityDemo
{
    public class WingFly : IFly
    {
        public string Fly()
        {
            return "通过翅膀飞翔";
        }
    }
}
namespace UnityDemo
{
    public class MachineFly : IFly
    {
        public string Fly()
        {
            return "通过机器飞翔";
        }
    }
}

四、新建实现类 Airplane,Bird实现ICanFly接口

using System;
using Unity.Attributes;

namespace UnityDemo
{
    public class Bird : ICanFly
    {
        [Dependency]
        public IFly Wing { get; set; }

        public void FlyToSpace()
        {
            Console.WriteLine("小鸟" + Wing.Fly());
        }
    }
}
using System;
using Unity.Attributes;

namespace UnityDemo
{
    public class Airplane : ICanFly
    {
        [Dependency]
        public IFly Machine { get; set; }

        public void FlyToSpace()
        {
            Console.WriteLine("飞机" + Machine.Fly());
        }
    }
}

 五、添加配置文件App.config




  
    

注:如果是从NuGet中添加的unity引用,则在程序运行时会出现以下错误:

C# Unity 依赖注入学习_第3张图片

解决方法:将配置文件的

  
    

修改为

  
    

六、主程序代码

using Microsoft.Practices.Unity.Configuration;
using System;
using System.Configuration;
using Unity;

namespace UnityDemo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            #region 原始方法

            //ICanFly airplane1 = new Airplane();

            //ICanFly bird1 = new Bird();

            //airplane1.FlyToSpace();
            //bird1.FlyToSpace();

            #endregion 原始方法

            #region 采用依赖注入 通过程序注册

            UnityContainer container = new UnityContainer();
            container.RegisterType();
            container.RegisterType();
            container.RegisterType();
            container.RegisterType();

            Bird bird2 = container.Resolve();
            Airplane airplane2 = container.Resolve();
            bird2.Wing = container.Resolve();
            airplane2.Machine = container.Resolve();
            bird2.FlyToSpace();
            airplane2.FlyToSpace();

            #endregion 采用依赖注入 通过程序注册

            #region 通过配置文件注册

            UnityConfigurationSection configuration = (UnityConfigurationSection)ConfigurationManager.GetSection(UnityConfigurationSection.SectionName);
            configuration.Configure(container, "Fly");
            Bird bird3 = container.Resolve();
            bird3.Wing = container.Resolve();
            Airplane airplane3 = container.Resolve();
            airplane3.Machine = container.Resolve();
            bird3.FlyToSpace();
            airplane3.FlyToSpace();

            #endregion 通过配置文件注册

            Console.Read();
        }
    }
}

源代码:https://github.com/ucow/UnityDemo.git

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