IOC理解
IoC(Inversion of Control):即控制反转,这是一种设计思想,指将对象的控制权交给IOC容器,由容器来实现对象的创建、管理,程序员只需要从容器获取想要的对象就可以了。DI(Dependency Injection),即依赖注入,他是IoC的一种具体实现方式。
IOC代码实现
Model类
cs
namespace IOCDemo.IOC
{
[IOCService]
internal class School
{
public string SchoolName { get; set; }
public Student Student { get; set; }
public void ShowMessage()
{
Console.WriteLine("创建School对象");
Student.ShowMessage();
}
}
internal class Student
{
public string StudentNo { get; set; }
public string StudentName { get; set;}
public void ShowMessage()
{
Console.WriteLine("创建Student对象");
}
}
}
IOC容器工程类
.Net8 IOC容器基本形态:
1、创建对象
2、存储对象 字典随机取对象,随机存对象性能高
3、获取对象
4、依赖注入(对象属性赋值)
5、对象过滤(特征)
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace IOCDemo.IOC
{
/// <summary>
/// IOC工程
/// 1、创建对象
/// 2、存储对象 字典随机取对象,随机存对象性能高
/// 3、获取对象
/// 4、依赖注入(对象属性赋值)
/// 5、对象过滤(特征)
/// 总结:完成.Net8 IOC容器基本形态
/// </summary>
internal class IOCFactory
{
private Dictionary<string,Object> IOCS = new Dictionary<string,Object>();
public IOCFactory() {
//不能直接new对象,违背开闭原则(对扩展开发,对修改关闭,如果有新的类,需要修改IOC工厂类)
Assembly assembly = Assembly.Load("IOCDemo");
Type[] types = assembly.GetTypes();
foreach (Type t in types)
{
IOCService service=t.GetCustomAttribute<IOCService>();
//5、过滤
if (service != null)
{
//1、创建对象
object obj = Activator.CreateInstance(t);
//同样违背开闭原则
//PropertyInfo propertyInfo = t.GetProperty("SchoolName");
//if (propertyInfo != null)
//{
// propertyInfo.SetValue(obj, new Student());
//}
//4、依赖注入
PropertyInfo[] properties = t.GetProperties();
foreach (var property in properties)
{
foreach (var type in types)
{
if (property.PropertyType.Equals(type))
{
object value = Activator.CreateInstance(type);
property.SetValue(obj, value);
}
}
}
//2、存储对象
IOCS.Add(t.FullName, obj);
}
}
}
/// <summary>
/// 3、获取IOC对象
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public object GetObject(string name)
{
return IOCS[name];
}
}
}
自定义特性类
cs
namespace IOCDemo.IOC
{
/// <summary>
/// 自定义特性
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
internal class IOCService:Attribute
{
}
}
实现
cs
using IOCDemo.IOC;
IOCFactory iOCFactory = new IOCFactory();
School school = (School)iOCFactory.GetObject("IOCDemo.IOC.School");
school.ShowMessage();