写点什么

.NET CORE 属性 DI 注入

作者:gogo
  • 2023-10-26
    广东
  • 本文字数:1159 字

    阅读完需:约 4 分钟

//使用: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

来源:稀土掘金

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发布于: 10 分钟前阅读数: 5
用户头像

gogo

关注

还未添加个人签名 2020-05-24 加入

态度决定人生高度.

评论

发布
暂无评论
.NET CORE 属性DI注入_gogo_InfoQ写作社区