一段代码

class Program
{
static void Main(string[] args)
{
var shop=new Shop();
shop.Add();
shop.Delete();
Console.ReadKey();
}
}
class Shop
{
readonly Log4NetServices _logServices; public Shop()
{
_logServices = new Log4NetServices();
} public void Add()
{
_logServices.Write("增加商品");
} public void Delete()
{
_logServices.Write("删除商品");
}
}

问题

  • 依赖具体Log4NetServices,要换成FileLogServices就要改

依赖

依赖就是依赖抽象

变形:

readonly ILogServices _logServices;

这样在实际使用中,不用管ILogServices的实现,由Shop的构造函数负责给具体实现

问题

  • Shop本身也不知道是用Log4NetServices还是FileLogServices,但使用者肯定是知道的。

注入

注入就是将你需要的东西传给你,不用你自己new

变形:

class Program
{
static void Main(string[] args)
{
var shop=new Shop(new Log4NetServices());
shop.Add();
shop.Delete();
shop=new Shop(new FileLogServices());
shop.Add();
shop.Delete();
Console.ReadKey();
}
}
class Shop
{
readonly ILogServices _logServices; public Shop(ILogServices logServices)
{
_logServices = logServices;
} public void Add()
{
_logServices.Write("增加商品");
} public void Delete()
{
_logServices.Write("删除商品");
}
}

问题:

  • 需要的人多了,我一个个new?
  • 需要的种类多了,我一个个new?
  • 能不能把new的东西放一起,需要的人统一从里面拿。

IOC

dotnetcore 的ioc示例

class Program
{
static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<ILogServices, Log4NetServices>();
var serviceProvider = serviceCollection.BuildServiceProvider();
var logServices = serviceProvider.GetService<ILogServices>();
var shop = new Shop(logServices);
shop.Add();
shop.Delete();
Console.ReadKey();
}
}

最新文章

  1. java web学习总结(二十五) -------------------JSP中的九个内置对象
  2. Spring Aspectj切入点语法定义
  3. Swift3.0都有哪些变化
  4. AndroidStudio NDK配置使用以及错误集合
  5. How to relocate tablespace directory
  6. onCreateOptionsMenu 和 onPrepareOptionsMenu 的区别
  7. 在xcode上搭建OpenGL3.x运行环境
  8. mysql 统计 每天累计用户数
  9. XPath总结一
  10. Android Animations动画使用详解
  11. ubuntu14.04通过将语音,耳机没有声音
  12. 【Java基础】String StringBuffer StringBuilder
  13. HDU-3032
  14. python的小基础
  15. 关于terraform的状态管理
  16. OSX 鼠标和键盘事件
  17. springboot~基于单元测试的mongodb
  18. 特殊计数序列——第一类斯特林(stirling)数
  19. SAP MM 无价值物料管理的一种实现思路
  20. 转://11g之后,通过v$wait_chains视图诊断数据库hang和Contention

热门文章

  1. C++7行代码实现求最大公约数
  2. 敏捷之旅--携程Scrum Master 新官上任三把火?
  3. 分布式CAP理论
  4. 力导向图(关系图) echarts的运用
  5. 第五章 Spring核心概念
  6. MSIL实用指南-struct的生成和操作
  7. 2019icpc南京网络赛_F_Greedy Sequence
  8. Java NIO系列之[说在前面的话]
  9. Jedis操作Redis--Hash类型
  10. k8s集群部分常见问题处理