这篇文章主要介绍了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
}
/// <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.net core的依赖注入容器中。
感谢你能够认真阅读完这篇文章,希望小编分享的“ASP.NET Core实现自动依赖注入的示例”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。