码迷,mamicode.com
首页 > 编程语言 > 详细

容器Unity实现IOC+DI

时间:2020-01-06 22:57:24      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:inject   bsp   param   依赖注入   name   image   构造   dep   summary   

/// <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}被构造。。。");
}
}

 

技术图片

容器Unity实现IOC+DI

标签:inject   bsp   param   依赖注入   name   image   构造   dep   summary   

原文地址:https://www.cnblogs.com/fblogs/p/12158858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!