针对部分工业工控机的软件更新迭代,还有软件统一化要求,对IOC技术进行研究,对比了几种IOC框架,本次研究的是微软自带的IOC框架Unity
Demo
https://gitee.com/chenheze90/L17_Unity
IOC介绍
IOC是Inversion of Control的简写,也就是控制反转的意思。有接触过设计模式和抽象开发的工程师都应该知道这一概念。指的是软件功能的实现过程都是通过操作抽象来实现。
常见的IOC框架还有AutoFac等
实例
首先创建一个控制台项目

在nuget中搜索Unity,选择如下。
本次使用的Unity版本是早期的版本。

Program的Main代码如下:
using Microsoft.Practices.Unity;
using System;
namespace UnityLearning
{
class Program
{
static void Main(string[] args)
{
// 创建简单单例
IUnityContainer container = new UnityContainer();//1、定义一个空容器
container.RegisterInstance<IStudent>(new Student() { Name = "张三" });
Console.WriteLine(container.Resolve<IStudent>().Name);
container.RegisterInstance<IStudent>(new Student() { Name = "李四" });
Console.WriteLine(container.Resolve<IStudent>().Name);
// 按照type注册
container.RegisterType<IStudent,Student>();
container.Resolve<IStudent>().Learn("按照type注册");
// 按照名称注册
container.RegisterInstance<IStudent>("领导",new Student() { Name = "张三" });
Console.WriteLine(container.Resolve<IStudent>("领导").Name);
container.RegisterInstance<IStudent>("领导", new Student() { Name = "李四" });
Console.WriteLine(container.Resolve<IStudent>("领导").Name);
}
}
}
运行效果如下:

unity其中有一个特点,它可以反复注册,而AutoFac不具备这个功能。如上代码所示,在注册之后可以重复注册,而不影响软件运行。

文章介绍了微软的IOC框架Unity的基本用法,包括创建单例、按类型和名称注册实例的示例。通过对比其他IOC框架,强调了Unity允许重复注册的特点。
2006

被折叠的 条评论
为什么被折叠?



