【小5聊】.Net Core基础之举例简单理解依赖注入

【实例化注入】

一般是注入实例化接口类,实例化类比较符合模式化面向对象化编程开发

【依赖注入好处】

解耦:表现在功能方法的改变,只需要修改一个地方或者尽可能少的地方

性能:用到的时候才实例化,节省内存空间的占用

【依赖注入分析】

以下仅为举例说明,实际业务肯定也不会这样子定义,辅助理解 

  实例化接口类 普通实例化类 依赖注入实例化接口类
基类

类:INoticeClass

方法:Send()

/

类:INoticeClass

方法:Send()

实现类

类:

EmailClass:INoticeClass、

PhoneMessage:INoticeClass、

WeiXinInfo:INoticeClass

方法:实现接口不同类型通知信息发送功能

类:

NoticeEmailClass、

NoticePhoneMessageClass、

NoticeWeiXinInfoClass

方法:Send()

类:EmailClass:INoticeClass

方法:实现接口通知信息发送功能

类:PhoneMessage:INoticeClass

方法:实现接口通知信息发送功能

A方法内

new EmailClass().Send();

new EmailClass().Send();

/

A方法外

INoticeClass notice=new EmailClass();

notice.Send("邮箱方法发送通知信息!");

NoticeEmailClass notice=new NoticeEmailClass();

notice.Send("邮箱方法发送通知信息!");

/
A构造函数

public AController()

{

  INoticeClass notice=new EmailClass();

  notice.Send("邮箱方法发送通知信息!");

}

public AController()

{

   NoticeEmailClass notice=new NoticeEmailClass();

   notice.Send("邮箱方法发送通知信息!");

}

private readonly INotice _notice;

public AController(INotice notice)

{

  _notice=notice; //此步骤已经是实例化

  _notice.Send("邮箱方法发送通知信息!");

}

B构造函数

public BController()

{

  INoticeClass notice=new EmailClass();

  notice.Send("邮箱方法发送通知信息!");

}

public AController()

{

   NoticeEmailClass notice=new NoticeEmailClass();

   notice.Send("邮箱方法发送通知信息!");

}

同上
C构造函数

public CController()

{

  INoticeClass notice=new EmailClass();

  notice.Send("邮箱方法发送通知信息!");

}

public AController()

{

   NoticeEmailClass notice=new NoticeEmailClass();

   notice.Send("邮箱方法发送通知信息!");

}

同上
startup启动类 / /

services.AddSingleton<INoticeClass, EmailClass>();

services.AddSingleton<INoticeClass, WeiXinInfo>();

备注 如果改为手机短信或微信通知,那么就需要修改三个地方(多个地方需要修改) 同左 只需要在启动类方法里修改,依赖注入不同的接口和实现类(所谓的注册服务)大大提高了解耦

思考:Singleton、Scoped、Transient,这三个类又有什么区别呢!

猜你喜欢

转载自blog.csdn.net/lmy_520/article/details/112805831