對上次的自動掃描進行改造

孤沉發表於2024-03-21

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.Key.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;
                }
            }
        }
    }

相關文章