排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术

net core中使用的依赖注入默认是:DependencyInjection
使用nuget下载:install-package Microsoft.Extensions.DependencyInjection
这里有一个设计原则:依赖于抽象,而不是具体的实现
使用也比较方便:
1:添加测试对象关系,也就是一个接口一个实现类,随便添加2个就可以
2:配置好类与接口的依赖关系
贴个代码方便复制
var serviceProvider = new ServiceCollection() .AddSingleton<IVisitorLogDAL, VisitorLogDAL>() .AddSingleton<IVisitorLogMQ, VisitorLogMQ>() .BuildServiceProvider();
3:通过依赖注入的容器得到对象就好
IVisitorLogMQ visitorLogMQ = serviceProvider.GetService<IVisitorLogMQ>(); visitorLogMQ.AddVisitLog();
VisitorLogMQ类中如果还有依赖,比如就是依赖于这个IVisitorLogDAL,我们也可以很方便的使用构造函数注入即可,
因为我们VisitorLogMQ对象是通过容器得到的,所以它所依赖的对象会被容器实例化的时候自动注入进去,这样使用起来就比较方便了
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)
评价