一段代码
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("删除商品"); } }
问题
依赖就是依赖抽象
变形:
readonly ilogservices _logservices;
这样在实际使用中,不用管ilogservices的实现,由shop的构造函数负责给具体实现
问题
注入就是将你需要的东西传给你,不用你自己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("删除商品"); } }
问题:
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(); } }
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论