对上次的自动扫描进行改造

1、现在有多个程序集

lib1、lib2、lib3、lib4

每个程序集都有类标注了特性ScanningAttribute

特性的代码是

 [AttributeUsage(AttributeTargets.Class, Inherited = false)]
 public class ScanningAttribute : Attribute
 {
     public string RegisterType { get; set; }
 }

lib1中存在

[Scanning(RegisterType="单例")]
public class Logger:ILogger{}
[Scanning(RegisterType="瞬时")]
public class HttpClientService:IHttpClientService{}

lib2中存在

[Scanning(RegisterType="单例")]
public class HomeRepository:IHomeRepository{}
[Scanning(RegisterType="瞬时")]
public class HomeService:IHomeService{}
[Scanning(RegisterType="花式")]
public class MainService:MainService{}

lib3和lib4都有和lib1,lib2类似的,我就不多写了

public void RegisterScannedTypes()
{
    var assemblies = new[]
{
    "Lib1", "Lib2", "Lib3", "Lib4",
};
    foreach (var assemblyName in assemblies)
    {
        //1、先是加载程序集
        var assembly = Assembly.Load(assemblyName);
        //2、找到类中标注了特性ScanningAttribute的所有类
        var typesToRegister = assembly.GetTypes()
        .Where(type => Attribute.IsDefined(type, typeof(ScanningAttribute)));
        // 3、创建一个字典,键是接口类型,值是实现类的类型 因为标注了特性ScanningAttribute的类只有一个接口
        var typeInterfaceDicts = typesToRegister.ToDictionary(type => type.GetInterfaces().First(), type => type);
       
        foreach (var typeInterDict in typeInterfaceDicts) 
        {
             //4、找到关于类中特性的RegisterType
		 var attribute = typeInterDict.Value.GetCustomAttribute<ScanningAttribute>(false);
            if (attribute != null)
            {
                switch (attribute.RegisterType)
                {
                    case "单例": _containerRegistry.RegisterInstance(typeInterDict.Key, typeInterDict.Value); break;
                    case "瞬时": _containerRegistry.RegisterScoped(typeInterDict.Key, typeInterDict.Value); break;
                    default:
                        break;
                }
            }
        }
    }

本文作者:孤沉

本文链接:https://www.cnblogs.com/guchen33/p/18086755

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   孤沉  阅读(8)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开