血浆爆裂,江宏恩老婆,终结者创世纪迅雷下载
目录
net core3.1是微软lts长期3年支持版本,正式发布于2019-12-03,并且在windows平台上支持了winfrom跟wpf桌面应用。本文介绍了使用winform时的第一步,将应用层以及orm涉及到的dbconfig,仓储层等依赖注入到容器中,并通过构造函数法从容器中调用实例,供给各窗体控件使用。
备注:本文的依赖注入讲解基于微软原生自带的di,通过ninject或者autofac可自行仿照操作,原理相通。
依赖注入是通过反转控制(ioc),设计模式属于代理模式+工厂模式,由serviceprovider根据实例接口或者实例类型调用,注入时生命周期的设置,控制实例化及配置实例生命周期,并返回实例给程序员调用,从而达到解放程序员的生产力,不用再去new 一个个实例,也不用去考虑实例之间的依赖关系,也不用去考虑实例的生命周期。实现,分为三个阶段,第一,程序员将服务注入服务容器阶段,第二程序员di实例调用阶段,第三serviceprovider服务管理者根据注入时的配置返回给程序对应的实例以及配置好实例的生命周期。
一张图就可以理解依赖注入实例调用过程
,感谢作者。
这里再向读者做个说明servicecollection是服务容器,serviceprovider是服务管理者,管理着服务容器,当程序发送抽象接口,或者类型时,serviceprovider会根据设置好的生命周期,返回需要的实例配置好实例的生命周期给程序员使用。
通过代理模式serviceprovider控制反转,他将持有控制权,将所有需要用到的接口,类型,反射出对应的实例,实例化以及设置好实例的生命周期,然后将控制权返还给程序员,不用再去new 一个个实例,也不用去考虑实例之间的依赖关系,也不用去考虑实例的生命周期,最终目的就是解放程序员的生产力,让程序员更轻松地写程序。
在注入的同时可以设置如下三种生命周期:
singleton
被实例化后就不会消失,程序运行期间只会有一个实例。
public interface isample { int id { get; } } public interface isampletransient : isample { } public interface isamplescoped : isample { } public interface isamplesingleton : isample { } public class sample : isampletransient, isamplescoped, isamplesingleton { private static int _counter; private int _id; public sample() { _id = ++_counter; } public int id => _id; }
public class startup { public void configureservices(iservicecollection services) { services.addtransient<isampletransient, sample>(); services.addscoped<isamplescoped, sample>(); services.addsingleton<isamplesingleton, sample>(); // singleton 也可以用以下方法注册 // services.addsingleton<isamplesingleton>(new sample()); } }
public class homecontroller : controller { private readonly isample _transient; private readonly isample _scoped; private readonly isample _singleton; public homecontroller( isampletransient transient, isamplescoped scoped, isamplesingleton singleton) { _transient = transient; _scoped = scoped; _singleton = singleton; } public iactionresult index() { viewbag.transientid = _transient.id; viewbag.transienthashcode = _transient.gethashcode(); viewbag.scopedid = _scoped.id; viewbag.scopedhashcode = _scoped.gethashcode(); viewbag.singletonid = _singleton.id; viewbag.singletonhashcode = _singleton.gethashcode(); return view(); } }
<table border="1"> <tr><td colspan="3">cotroller</td></tr> <tr><td>lifetimes</td><td>id</td><td>hash code</td></tr> <tr><td>transient</td><td>@viewbag.transientid</td><td>@viewbag.transienthashcode</td></tr> <tr><td>scoped</td><td>@viewbag.scopedid</td><td>@viewbag.scopedhashcode</td></tr> <tr><td>singleton</td><td>@viewbag.singletonid</td><td>@viewbag.singletonhashcode</td></tr> </table>
可自行做测试,具体可参考
如上,实例是在homecontroller中通过接口来调用实例的,因此修改程序只需要在实例中需改,而不需要在调用层修改。
这符合了6大程序设计原则中的依赖倒置原则:
1.高层模块不应该依赖于低层模块,两者都应该依赖其抽象
展现层controller没有依赖model层sample类,两者都依赖了sample的接口抽象isample,isampletransient,isamplescoped,isamplesingleton.
2.抽象不应该依赖于细节
接口层只定义规范,没有定义细节。
public interface isample { int id { get; } } public interface isampletransient : isample { } public interface isamplescoped : isample { } public interface isamplesingleton : isample { }
3.细节应该依赖于抽象
di中取实例依赖于接口:
isampletransient transient;
服务类的实现也依赖于接口:
public class sample : isampletransient, isamplescoped, isamplesingleton { private static int _counter; private int _id; public sample() { _id = ++_counter; } public int id => _id; }
使程序员不用再去考虑各个di实例之间的依赖,以及new很多个相互依赖的实例。
在依赖注入的服务调用的地方,容器管理者serviceprovider从程序员手中取得控制权,控制所需服务实例化以及设置好他的生命周期,然后返回给程序员。
根据di的生命周期设置,根据接口或者类型,生产出各种生命周期的实例,需要注意的是这里有可能是同一实例(scope的单次请求中,或者transient生命周期),transient每次产生的都是新的实例。
笔者发现在最新的vs发行版中,能创建winform工程,但却无法打开设计器,也无法打开winform的工具箱。怎么办?
在中提到在vs16.5预览版中支持了winform设计器,根据博客中提到,需要在此下载链接下载vs16.5预览版。
netcore3.1 winform截图如下:
可以看到控件明显比基于dot net framework的好看很多,同时,工具箱中的控件很少,微软把一些老的已经有替代的控件删除了,并且以后会慢慢加入一些必要的控件。
net core mvc容器是自动创建好的,只需要在configureservices方法里配置服务即可。而在net core3.1上创建了winform工程之后窗体是new实例,以单例的形式跑的。容器的配置创建,都需要自己来做。
static class program { /// <summary> /// the main entry point for the application. /// </summary> [stathread] static void main() { application.sethighdpimode(highdpimode.systemaware); application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); application.run(new form1()); } }
那如果需要向form窗体中注入服务就需要在new实例的时候就传入实参。
[stathread] static void main() { application.sethighdpimode(highdpimode.systemaware); application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); var services = new servicecollection(); configureservices(services); using (serviceprovider serviceprovider = services.buildserviceprovider()) { var logg = services.buildserviceprovider().getrequiredservice<ilogger<form1>>(); var businessobject = services.buildserviceprovider().getrequiredservice<ibusinesslayer>(); application.run(new form1(logg, businessobject)); } }
调用的时候用窗体的构造函数调用服务接口即可。
public partial class form1 : form { private readonly ilogger _logger; private readonly ibusinesslayer _business; public form1(ilogger<form1> logger, ibusinesslayer business) { _logger = logger; _business = business; initializecomponent(); } private void button1_click(object sender, eventargs e) { try { _logger.loginformation("form1 {businesslayerevent} at {datetime}", "started", datetime.utcnow); // perform business logic here _business.performbusiness(); messagebox.show("hello .net core 3.0 . this is first forms app in .net core"); _logger.loginformation("form1 {businesslayerevent} at {datetime}", "ended", datetime.utcnow); } catch (exception ex) { //log technical exception _logger.logerror(ex.message); //return exception repsponse here throw; } } }
本方法摘自
这样至少有两个缺点:
当form1中需要从di中增加接口实例调用时,也需要在如下调用代码中增加对应实参。而且实参多了,会很冗长。
application.run(new form1(logg, businessobject));
把form的类型也以单例的形式注入到容器中,调用时,获取mainform类型的服务。这样此服务实例依赖于其他的服务。serviceprovider容器管理者会自动解决好服务之间的依赖关系,并将对应的服务实例化并根据生命周期设置好,交给程序员去使用。问题完美解决。
此思路有借鉴于以下两篇文章
微软msdn
这里向大家重点推荐下stackoverflow,这个基于世界级的程序员论坛,在我遇到很多的疑难杂症,孤立无援的时候,他都会给予我解决问题的思路,方向甚至方案,再次致敬感谢stackoverflow,同时也感谢谷歌。
private static void configureservices(servicecollection services) { //app services.applicationserviceioc(); //infra //repo services.infrastructureorm<dapperioc>(); //presentation 其他的窗体也可以注入在此处 services.addsingleton(typeof(mainform)); }
这里需要说明的是,笔者这里的ioc是应用层,展现层,仓储层分层注入了,每层都写了servicecollection服务容器的静态方法,所以服务可以在各层注入,读者可以不去追究,将自己的服务注入在此即可。
分层注入:
分层注入简单实现
cameradm_service注册在了applicationserviceioc,applicationserviceioc注册在了configureservices。这就是我刚说的分层注入每层的依赖。
public static class servicesioc { public static void applicationserviceioc(this iservicecollection services) { services.addscoped(typeof(iservicebase<>), typeof(servicebase<>)); services.addscoped<icameradm_service, cameradm_service>(); } }
重点关注
将窗体类型注入,当然后续加入其它窗体也可用同样方法进行注入。
services.addsingleton(typeof(mainform));
var services = new servicecollection();
configureservices(services);
此步骤调用的就是3.4.1中的方法。
var serviceprovider = services.buildserviceprovider();
向服务管理者请求mainform类型的实例服务,具体调用过程详见2.1。
application.run(serviceprovider.getservice<mainform>());
这一步是重点,也是winform跟mvc使用上的区别,但是本质却是相同的,都是由serviceprovider管理着wpf,winform或者mvc这些实例以及他们对应的类型,只不过mvc容器已经创建好了,容器管理者serviceprovider也已经创建好了,直接往容器里add服务即可,而winform,wpf,net core控制台程序需要我们自己去往容器里添加注册服务,并且创建容器管理者serviceprovider。因为servicecollection容器是死的,只有创建了serviceprovider容器管理者这个代理角色,容器才能体现出他的价值。而只有serviceprovider,没有servicecollection里的服务也是毫无意义的。
3.4.1到3.4.5整体代码如下:
static class program { /// <summary> /// the main entry point for the application. /// </summary> [stathread] static void main() { application.sethighdpimode(highdpimode.systemaware); application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); //创建服务容器对象 var services = new servicecollection(); //添加服务注册 configureservices(services); //构建serviceprovider对象 var serviceprovider = services.buildserviceprovider(); //向服务管理者请求mainform类型的实例服务 application.run(serviceprovider.getservice<mainform>()); } private static void configureservices(servicecollection services) { //app services.applicationserviceioc(); //infra //repo services.infrastructureorm<dapperioc>(); //presentation 其他的窗体也可以注入在此处 services.addsingleton(typeof(mainform)); } }
public partial class mainform : form { icameradm_service _cameradm_service; public mainform(icameradm_service cameradm_service) { _cameradm_service = cameradm_service; initializecomponent(); } private async void button1_click(object sender, eventargs e) { messagebox.show(_cameradm_service.getallcamerainfo().tolist().count().tostring()); var _camera =await _cameradm_service.getallincludingtasksasync(); //textbox1.text = _camera.tolist().count().tostring(); var _camerano3 = await _cameradm_service.getbyidasync(3); textbox1.text = _camerano3.installtime.tostring(); } }
点击按钮之后从摄像头服务中获取到了摄像头的数量。
点击确定之后从摄像头服务中获取到了3号摄像头的安装时间。
3.6属于12/23/13:33新增,为了答复1楼网友 编程老油条所问问题。
问题如下:
假设在mainform中的button1_click,还需要打开其他窗口,要如何实现?(只能往 mainform 中传递serviceprovider吗?)
把serviceprovider设计成全局静态的,可设计成单例模式或直接放在main的属性中,供全局任意子窗体访问获取di实例即可,当然同时,其他窗体也需要注入到容器中。
注入生命周期为瞬时的form1类型。
services.addtransient(typeof(form1));
private static void configureservices(servicecollection services) { //app services.applicationserviceioc(); //infra //repo services.infrastructureorm<dapperioc>(); //presentation 其他的窗体也可以注入在此处 services.addsingleton(typeof(mainform)); services.addtransient(typeof(form1)); }
因为form1是mainform的子窗体,而mainform设置成了单例模式,所以在mainform中打开form1是属于同一次请求,姑不能用addsingleton跟addscope模式。如果使用以上两种模式,会报如下异常:
比如设置form1生命周期为单例模式
services.addsingleton(typeof(mainform)); services.addsingleton(typeof(form1));
第一次调用正常,
关闭form1第二次点击mainform的button1时,报如下异常:
因为是单例模式,我们关闭了form1,mainform还在,再次点击button1,会找不到生命周期是单例模式的form1实例,就会报如上异常。
修改成
services.addtransient(typeof(form1));
问题得到完美解决,无论关闭多少次form1,都能通过mainform的button1调用打开form1。
修改serviceprovider为program静态类的公用属性(全局),以给子窗体或其他winform中的组件来容器服务者获取di实例
public static iserviceprovider serviceprovider { get; set; }
program.cs全部代码如下。
static class program { public static iserviceprovider serviceprovider { get; set; } /// <summary> /// the main entry point for the application. /// </summary> [stathread] static void main() { application.sethighdpimode(highdpimode.systemaware); application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); //创建服务容器对象 var services = new servicecollection(); //添加服务注册 configureservices(services); //构建serviceprovider对象 serviceprovider = services.buildserviceprovider(); //向服务管理者请求mainform类型的实例服务 application.run(serviceprovider.getservice<mainform>()); } private static void configureservices(servicecollection services) { //app services.applicationserviceioc(); //infra //repo services.infrastructureorm<dapperioc>(); //presentation 其他的窗体也可以注入在此处 services.addsingleton(typeof(mainform)); services.addtransient(typeof(form1)); } }
到program服务管理者属性手中拿到对应所需类型的设置好生命周期的form1实例。显示form1。
public partial class mainform : form { public mainform() { initializecomponent(); } private async void button1_click(object sender, eventargs e) { var child = (form)program.serviceprovider.getservice((typeof(form1))); child.show(); } }
form1调用camera服务
此处同3.5
public partial class form1 : form { icameradm_service _cameradm_service; public form1(icameradm_service cameradm_service) { _cameradm_service = cameradm_service; initializecomponent(); } private async void button1_click(object sender, eventargs e) { messagebox.show(_cameradm_service.getallcamerainfo().tolist().count().tostring()); } }
本来就想写篇短文,谁知道洋洋洒洒还写得有点长。本文如果大家读了有疑惑,请提出来,我会耐心解答;如果知识点上有不妥当不正确或者不同见解的地方,也恳请指出,我同时也很渴望进步。最后祝大家冬至安康,阖家幸福。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Blazor server side 自家的一些开源的, 实用型项目的进度之 CEF客户端
.NET IoC模式依赖反转(DIP)、控制反转(Ioc)、依赖注入(DI)
vue+.netcore可支持业务代码扩展的开发框架 VOL.Vue 2.0版本发布
网友评论