ASP.NET Core实现自动依赖注入
网络编程 2021-07-04 22:41www.168986.cn编程入门
这篇文章主要介绍了ASP.NET Core实现自动依赖注入的示例,帮助大家更好的理解和学习使用.技术,感兴趣的朋友可以了解下
在开发.NET Core web服务的时候,我们习惯使用自带的依赖注入容器来进行注入。
于是就会经常进行一个很频繁的的重复动作定义一个接口->写实现类->注入
有时候会忘了写Add这一步,看到屏幕上的报错一脸懵逼,然后瞬间反应过来忘了注入了。赶紧补上serviceCollection.AddXXX这句话
虽然说有很多开源框架已经实现了类似的工作,比如AutoFac,Unity等依赖注入框架。这些库都太庞大了,我个人还是喜欢轻量级的实现。
定义一个枚举
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class AutoInjectAttribute : Attribute { public AutoInjectAttribute(Type interfaceType, InjectType injectType) { Type = interfaceType; InjectType = injectType; } public Type Type { get; set; } /// <summary> /// 注入类型 /// </summary> public InjectType InjectType { get; set; } }
定义三种注入类型
/// <summary> /// 注入类型 /// </summary> public enum InjectType { Scope, Single, Transient }
扫描运行目录下所有的dll,进行自动注入
/// <summary> /// 自动依赖注入 /// </summary> public static class AutoInject { /// <summary> /// 自动注入所有的程序集有InjectAttribute标签 /// </summary> /// <param name="serviceCollection"></param> /// <returns></returns> public static IServiceCollection AddAutoDi(this IServiceCollection serviceCollection) { var path = AppDomain.CurrentDomain.BaseDirectory; var assemblies = Directory.GetFiles(path, ".dll").Select(Assembly.LoadFrom).ToList(); foreach (var assembly in assemblies) { var types = assembly.GetTypes().Where(a => a.GetCustomAttribute<AutoInjectAttribute>() != null) .ToList(); if (types.Count <= 0) continue; foreach (var type in types) { var attr = type.GetCustomAttribute<AutoInjectAttribute>(); if (attr?.Type == null) continue; switch (attr.InjectType) { case InjectType.Scope: serviceCollection.AddScoped(attr.Type, type); break; case InjectType.Single: serviceCollection.AddSingleton(attr.Type, type); break; case InjectType.Transient: serviceCollection.AddTransient(attr.Type, type); break; default: throw new ArgumentOutOfRangeException(); } } } return serviceCollection; } }
使用自动依赖注入功能
public void ConfigureServices(IServiceCollection services) { services.AddAutoDi(); }
public interface ITest { string Say(); } [AutoInject(typeof(ITest),InjectType.Scope)] public class Test : ITest { public String Say() { return "test:"+DateTime.Now.ToString(); } }
运行程序,所有的贴有AutoInject
的所有的实现类,都会被注入到asp. core的依赖注入容器中。
以上就是ASP.NET Core实现自动依赖注入的详细内容,更多关于ASP.NET Core 自动依赖注入的资料请关注狼蚁SEO其它相关文章!
编程语言
- 宿迁百度关键词排名指南:实现精准营销的关键
- 四川SEO优化怎么做网络推广
- 立昂技术备案老域名收购:如何为您的业务赋能
- 安徽百度关键词seo贵不贵,一般需要多少钱
- 吉林百度快照排名怎么做电话营销
- 多伦新手做SEO怎么做
- 甘肃优化关键词排名推广怎么做论坛营销
- 沙雅SEO网站推广:提升您的在线可见性
- 四川SEO优化如何提升销售额和销售量
- 聂荣网站排名优化:提升网站可见性的全方位指
- 涞水SEO:提升地方企业在线可见性的策略
- 辽宁百度seo排名怎样做网站排名
- 临湘哪有关键词排名优化:提升网站可见度的关
- 黑龙江百度网站优化有没有优惠
- 凉城优化关键词排名推广:提升您的网络可见性
- 萝北整站优化:提升您网站流量和排名的全面指