一步步到IOC(一步步到了知县位又恐官势位低)

网友投稿 219 2022-08-04

一步步到IOC(一步步到了知县位又恐官势位低)

一段代码

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();

var serviceProvider = serviceCollection.BuildServiceProvider();

var logServices = serviceProvider.GetService();

var shop = new Shop(logServices);

shop.Add();

shop.Delete();

Console.ReadKey();

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:一个static和面试官扯了一个小时,舌战加强版
下一篇:C#面向对象之继承(cctv5体育节目表)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~