加入收藏 | 设为首页 | 会员中心 | 我要投稿 51站长网 (https://www.51zhanzhang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
站内搜索:
当前位置: 首页 > 站长学院 > Asp教程 > 正文

ASP.NET Core 奇淫技巧之伪属性注入的实现

发布时间:2020-08-21 11:18:28 所属栏目:Asp教程 来源:网络整理
导读:这篇文章主要介绍了ASP.NET Core 奇淫技巧之伪属性注入的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下

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<TService, TImpl>(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<ILoggerFactory>().CreateLogger(implType); } return implInstance; }); return services; }

注册测试服务

Controller 注入测试服务

运行测试

七.结束

(编辑:ASP站长)

【免责声明】本站内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关内容
未处理完善
    无相关信息
未处理完善