目前ConditionOnClass使用的是Type.GetType()
来获取:
|
internal static bool FindClass(this string classPath) |
|
{ |
|
try |
|
{ |
|
return Type.GetType(classPath) != null; |
|
} |
|
catch (Exception) |
|
{ |
|
return false; |
|
} |
|
} |
在8. 有条件的DI也有提到,入参应为“类的完整名称”,而这个所谓的名称其实是AssemblyQualifiedName。官方的定义是:
The assembly-qualified name of a type consists of the type name, including its namespace, followed by a comma, followed by the display name of the assembly. The display name of an assembly is obtained using the Assembly.FullName property.
即,AssemblyQualifiedName由①命名空间+类名、②逗号、③程序集名组成。
它长这样(来自官方示例代码):
using System;
class MyAssemblyClass
{
public static void Main()
{
Type objType = typeof(Array);
// Print the assembly full name.
Console.WriteLine($"Assembly full name:\n {objType.Assembly.FullName}.");
// Print the assembly qualified name.
Console.WriteLine($"Assembly qualified name:\n {objType.AssemblyQualifiedName}.");
}
}
// The example displays the following output if run under the .NET Framework 4.5:
// Assembly full name:
// mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
// Assembly qualified name:
// System.Array, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
而对于Type.GetType(string typeName)
,官方有说明:
If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and mscorlib.dll/System.Private.CoreLib.dll, in that order. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. If the assembly has a strong name, a complete assembly name is required.
https://learn.microsoft.com/en-us/dotnet/api/system.type.gettype?view=net-8.0#system-type-gettype(system-string)
经过测试,入参时对于跨程序集的类,还需要加上逗号分隔的第二段部分,也就是程序集名才能正常获取。例如在当前程序集MyProject
获取跨程序集的MyProject.Common
下的MyProject.Common.Configs.MyConfig
,就需要写成
Type.GetType("MyProject.Common.Configs.MyConfig, MyProject.Common");
但因为对于Autofac.Annotation来说使用者是第三方程序集,因此使用者在使用ConditionOnClass时始终需要写上程序集名。
此外对于逗号前后的空格官方也有要求,即逗号前不能有空格但逗号后可以有空格:
Spaces are relevant in all type name components except the assembly name. In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.
此外还有关于泛型参数和可空类型要怎么写的说明,详见https://learn.microsoft.com/en-us/dotnet/api/system.type.gettype?view=net-8.0#system-type-gettype(system-string)
建议完善下Wiki,以免有人摸不着头脑。