.NET IOC Framework-Getting Started with Unity Container Fundamentals

[C# Advanced Syntax Feature Collection]

https://blog.csdn.net/qq_34202873/article/details/91043366


C# IOC container Unity

Inversion of Control (Inversion of Control, English abbreviation IoC) is an important object-oriented programming law to reduce the coupling problem of computer programs, and it is also the core of the lightweight Spring framework. Inversion of control is generally divided into two types, Dependency Injection (DI) and Dependency Lookup. Dependency injection is widely used.

Unity component URL: http://unity.codeplex.com/

1. Load related dependencies first: NuGet

! ! The key point must be noted! !

Use Unity.Interception 5.1.0 (don't use the latest, a lot of god BUG)

Insert picture description here

A total of the following four are required, install directly

2. Problem description

Prepare a few classes first

	/// <summary>
	/// 班级接口
	/// </summary>
	public interface IClass
	{
		string ClassName { get; set; }
		   void ShowInfo();
	}
	/// <summary>
	/// 计科班
	/// </summary>
	public class CbClass : IClass
	{
		public string ClassName { get; set; }
		public void ShowInfo()
		{
			Console.WriteLine("计科班:{0}", ClassName);
		}
	}
	/// <summary>
	/// 电商班
	/// </summary>
	public class EcClass : IClass
	{
		public string ClassName { get; set; }
		public void ShowInfo()
		{
			Console.WriteLine("电商班:{0}", ClassName);
		}
	}

Many people like this when initializing an instance

CbClass cbclass = new CbClass();

This is the case when using the dependency inversion principle

IClass class = new CbClass();

If it’s better, just build a simple factory to encapsulate it.

var class = Factory.CreateClass();

3. Problem solving

But once there are more classes, you have to modify the factory every time you add classes, which becomes very complicated. Here we use dependency injection to solve this problem.

 public static void ContainerCodeTest1()
{
    IUnityContainer container = new UnityContainer();
//默认注册(无命名),如果后面还有默认注册会覆盖前面的
container.RegisterType&lt;IClass, CbClass&gt;();

//命名注册
container.RegisterType&lt;IClass, EcClass&gt;("ec");

//解析默认对象
IClass cbClass = container.Resolve&lt;IClass&gt;();
cbClass.ShowInfo();

//指定命名解析对象
IClass ecClass = container.Resolve&lt;IClass&gt;("ec");           
ecClass.ShowInfo();

//获取容器中所有IClass的注册的已命名对象
IEnumerable&lt;IClass&gt; classList = container.ResolveAll&lt;IClass&gt;();
foreach (var item in classList)
{
    item.ShowInfo();
}

4. Use the configuration file to solve

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <!--定义类型别名-->
    <aliases>
      <add alias="IClass" type="ConsoleApplication1.UnityDemo.IClass,ConsoleApplication1" />
      <add alias="CbClass" type="ConsoleApplication1.UnityDemo.CbClass,ConsoleApplication1" />
      <add alias="EcClass" type="ConsoleApplication1.UnityDemo.EcClass,ConsoleApplication1" />
    </aliases>
    <!--容器-->
    <container name="FirstClass">
      <!--映射关系-->
      <register type="IClass"  mapTo="CbClass"></register>
      <register type="IClass" name="ec" mapTo="EcClass"></register>
    </container>
  </unity>
</configuration>

Data analysis method

public static void ContainerConfigurationTest1()
{
    IUnityContainer container = new UnityContainer();
    string configFile = "http://www.cnblogs.com/UnityDemo/Constructor/Unity.config";
    var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
    //从config文件中读取配置信息
    Configuration configuration =
        ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
    //获取指定名称的配置节
    UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
//载入名称为FirstClass 的container节点
container.LoadConfiguration(section, "FirstClass");

//Resolve the default object
IClass cbClass = container.Resolve<IClass>();
cbClass.ShowInfo();

//指定命名解析对象
IClass ecClass = container.Resolve&lt;IClass&gt;("ec");           
ecClass.ShowInfo();

//获取容器中所有IClass的注册的已命名对象
IEnumerable&lt;IClass&gt; classList = container.ResolveAll&lt;IClass&gt;();
foreach (var item in classList)
{
    item.ShowInfo();
}

The article specific implementation code reference: http://www.cnblogs.com/qqlin/

Reprinted from [C#/.NET IOC Framework-Getting Started with Unity Container Basics] (https://blog.csdn.net/qq_34202873/article/details/85042409)

Guess you like

Origin blog.csdn.net/sunzheng176/article/details/114204984