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;
}
}
}
}
标签:RegisterType,改造,class,扫描,上次,var,type,public,typeInterDict
From: https://www.cnblogs.com/guchen33/p/18086755