(精华)2020年7月21日 ASP.NET Core 容器伪属性注入
发布日期:2021-06-29 15:08:10
浏览次数:3
分类:技术文章
本文共 1916 字,大约阅读时间需要 6 分钟。
为 Controller 实现伪属性注入
Controller 默认是不会通过自带容器来 Resolve&Activate 的,是通过MVC自身管理的。可以通过调用 AddControllersAsServices()方法来让 Controller 使用自带容器。
services.AddControllers().AddControllersAsServices();
AddControllersAsServices源码如下
定义 Controller 基类 Controller 继承基类 改造 Controller 激活器 替换默认 Controller 激活器services.AddControllers().AddControllersAsServices();services.Replace(ServiceDescriptor.Transient()); //替换默认 Controller 激活器
为 Application Service 实现伪属性注入
只是以 Application Service 来作为讲解,同理可举一反三到其他地方。Application Service 属于领域驱动分层架构中的一层,如不了解,可自行查找资料。
定义应用服务基类接口
public interface IAppService{ ILogger Logger { get; set; }}public class AppService:IAppService{ public ILogger Logger { get; set; }}
定义具体服务,以 User 服务为例
public interface IUserAppService:IAppService{ void Create();}public class UserAppService : AppService,IUserAppService{ public void Create() { Logger.LogInformation("来自 Application Service 的日志"); }}
定义特殊的注册服务的方法,以便实现 Resolve 为 Logger 赋值
public static class ServiceExtensions{ public static IServiceCollection AddApplicationService(this IServiceCollection services) where TService:IAppService where TImpl:AppService { services.AddApplicationService(typeof(TService), typeof(TImpl)); return services; } // 可以反射程序集调用此方法实现批量自动注册应用服务 public static IServiceCollection AddApplicationService(this IServiceCollection services, Type serviceType,Type implType) { services.AddTransient(serviceType, sp => { //获取服务实现的实例 var implInstance = ActivatorUtilities.CreateInstance(sp, implType); ; if (implInstance is AppService obj) { //为 Logger 赋值 obj.Logger= sp.GetRequiredService ().CreateLogger(implType); } return implInstance; }); return services; }
注册测试服务
转载地址:https://codeboy.blog.csdn.net/article/details/107491709 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
表示我来过!
[***.240.166.169]2024年04月18日 01时25分54秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
中国信息化发展八大趋势(四)
2019-04-29
电商大战二十年
2019-04-29
神奇的麦考林
2019-04-29
centos7使用rpm安装mysql遇到的error: Failed dependencies: mysql-community-common(x86-64) 5.7.9 is needed
2019-04-29
spark报错:warn util.utils::service ‘sparkUI‘ can not bind on part 4040.Attempting port 4041.4042等错误
2019-04-29
Error getting authority: Error initializing authority: Could not connect: No such file or directory
2019-04-29
编程程软件测试思维方式:如何科学制定测试计划
2019-04-29
BLE蓝牙4.0串口调试助手
2019-04-29
树莓派WIFI设置
2019-04-29
用vcgencmd获取树莓派硬件状态数据
2019-04-29
IIS 多域名多张证书配置
2019-04-29
树莓派LINUX 截屏
2019-04-29
树莓派Raspberry Pi的嵌入式QT平台
2019-04-29
apache https
2019-04-29
Debian Jessie安装支持HTML5音视频的Chromium浏览器听百度音乐
2019-04-29
nanopi2 启动信息
2019-04-29
POS打印机驱动大全
2019-04-29
phpstudy https
2019-04-29
centos apache 最新版HTTPS配置
2019-04-29