容器Unity实现IOC+DI

/// <summary>
/// IOC控制反转:正常情况下,程序开发过程中,是上端调用下端,依赖下端
/// 依赖倒置原则->上端不要依赖下端,要依赖下端的抽象
/// 上端只依赖抽象,细节交给第三方工厂来决定,这就是IOC,就是控制反转->系统架构可以更稳定,支持扩展
/// DI依赖注入:称之为实现IOC的手段,而IOC是一种效果
/// 构造对象时,将对象依赖的元素自动初始化,就叫依赖注入
/// 三种注入(时间顺序):
/// 1.构造函数注入
/// 2.属性注入
/// 3.方法注入
/// 实现:反射+特性
///
/// 没有DI就没有IOC
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//直接用容器代替工厂
//1.NUget添加Unity引用
//IUnityContainer container = new UnityContainer();//实例化容器
//container.RegisterType<IPhone, AndroidPhone>();//初始&注册&映射->将细节AndroidPhone映射到抽象类IPhone
//IPhone phone = container.Resolve<IPhone>();//实例化IPhone
//phone.Call();

IUnityContainer container = new UnityContainer();//实例化容器
container.RegisterType<IPhone, ApplePhone>();//初始&注册&映射->将细节AndroidPhone映射到抽象类IPhone
container.RegisterType<IHeadPhone, HeadPhone>();
container.RegisterType<IMicroPhone, MicroPhone>();
container.RegisterType<IPower, Power>();
IPhone phone = container.Resolve<IPhone>();//实例化IPhone
phone.Call();//构造ApplePhone实例的同时,把三个属性都初始化了一番,这就叫依赖注入
Console.ReadLine();
}

public interface IPhone
{
void Call();
IMicroPhone Microphone { get; set; }
IHeadPhone HeadPhone { get; set; }
IPower Power { get; set; }
}

public class AndroidPhone : IPhone
{
public IMicroPhone Microphone { get; set; }
public IHeadPhone HeadPhone { get; set; }
public IPower Power { get; set; }

public AndroidPhone()
{
Console.WriteLine("{0}构造函数", this.GetType().Name);
}
public void Call()
{
Console.WriteLine($"{this.GetType().Name}打电话");
}
}

public class ApplePhone:IPhone
{
[Dependency]//属性注入
public IMicroPhone Microphone { get; set; }
public IHeadPhone HeadPhone { get; set; }
public IPower Power { get; set; }
public ApplePhone()
{
Console.WriteLine("{0}构造函数", this.GetType().Name);
}

[InjectionConstructor]//构造函数注入:可以不要特性,默认调用参数个数最多的
public ApplePhone(IHeadPhone headPhone)
{
this.HeadPhone = headPhone;
Console.WriteLine("{0}带参数的构造函数", this.GetType().Name);
}

public void Call()
{
Console.WriteLine($"{this.GetType().Name}打电话");
}

[InjectionMethod]
public void Init(IPower iPower)
{
this.Power = iPower;
}
}

public class HeadPhone:IHeadPhone
{
public HeadPhone()
{
Console.WriteLine($"{this.GetType().Name}被构造。。。");
}
}

public class MicroPhone: IMicroPhone
{
public MicroPhone()
{
Console.WriteLine($"{this.GetType().Name}被构造。。。");
}
}

猜你喜欢

转载自www.cnblogs.com/fblogs/p/12158858.html