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

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

发布时间:2020-08-21 12:15:09 所属栏目:编程 来源:网络整理
导读:这篇文章首要先容了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 注入测试处事

运行测试

七.竣事

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读