.NET CORE 属性 DI 注入
//使用:services.AddDIServices();
///
/// 标记服务
///
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public class DIServicesAttribute : Attribute
{
///
/// 生命周期
///
public ServiceLifetime Lifetime { get; set; } = ServiceLifetime.Singleton;
///
/// 指定服务类型
///
public Type ServiceType { get; set; }
///
/// 是否可以从第一个接口获取服务类型
///
public bool InterfaceServiceType { get; set; } = true;
///
/// 服务(实现)唯一标识
///
public string Identifier { get; set; }
public DIServicesAttribute(){}
public DIServicesAttribute(Type serviceType) : this(serviceType, ServiceLifetime.Singleton, null, false){}
public DIServicesAttribute(ServiceLifetime serviceLifetime) : this(null, serviceLifetime, null, true){}
public DIServicesAttribute(string identifier) : this(null, ServiceLifetime.Singleton, identifier, true){}
private DIServicesAttribute(Type serviceType, ServiceLifetime serviceLifetime, string identifier, bool interfaceServiceType){ServiceType = serviceType;Lifetime = serviceLifetime;Identifier = identifier;InterfaceServiceType = interfaceServiceType;}
}
public static class DIServiceExtensions{///
/// 注册应用程序域中所有有 DIServices 特性的类
///
///
public static void AddDIServices(this IServiceCollection services)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypes())
{
foreach (var serviceAttribute in type.GetCustomAttributes())
{
if (serviceAttribute != null)
{
var serviceType = serviceAttribute.ServiceType;
//类型检查,如果 type 不是 serviceType 的实现或子类或本身//运行时 type 将无法解析为 serviceType 的实例 if (serviceType != null && !serviceType.IsAssignableFrom(type)){serviceType = null;}
if (serviceType == null && serviceAttribute.InterfaceServiceType){//serviceType = type.GetInterfaces().FirstOrDefault();serviceType = type.GetInterfaces().LastOrDefault();}
if (serviceType == null){serviceType = type;}
switch (serviceAttribute.Lifetime){case ServiceLifetime.Singleton:services.AddSingleton(serviceType, type);break;case ServiceLifetime.Scoped:services.AddScoped(serviceType, type);break;case ServiceLifetime.Transient:services.AddTransient(serviceType, type);break;default:break;}}}}}}
}
作者:宇宙 007
链接:https://juejin.cn/post/7289047550739972156
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
版权声明: 本文为 InfoQ 作者【gogo】的原创文章。
原文链接:【http://xie.infoq.cn/article/29b921d8676a8ffa03eabfa81】。文章转载请联系作者。
评论