IoC: Simple application of unity

What is Unity?
Unity is a lightweight and extensible dependency injection container developed by the patterns&practices team.

Unity features
1. It provides a mechanism to create (or assemble) object instances, and these object instances may also contain other dependent object instances.

2. Unity allows pre-configured objects to be injected into the class to achieve the function of inversion of control (Ioc). In Unity, constructor injection, property setter injection and method call injection are supported.

3. The architecture that supports the container. A container can have child containers, allowing object positioning queries from the child container to the parent container.

4. The container can be prepared and configured through the configuration file.

5. It will not affect the definition of the class (except property setting value injection and method injection), which is also a manifestation of lightweight containers.

6. Support custom container extension.

Unity practice
Create a new console program, and Nuget installs Unity and
Insert picture description here
writes the class 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);
		}
	}

Generally when initializing an instance like this

CbClass cbclass = new CbClass();

Use the dependency inversion principle

IClass class = new CbClass();

Build a simple factory package again

var class = Factory.CreateClass();

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<IClass, CbClass>();
  
    //命名注册
    container.RegisterType<IClass, EcClass>("ec");

    //解析默认对象
    IClass cbClass = container.Resolve<IClass>();
    cbClass.ShowInfo();

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

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

Guess you like

Origin blog.csdn.net/dingmengwei/article/details/114205021