我如何伪造 Assembly.LoadFile 和 Assembly.GetTypes?
How can I fake Assembly.LoadFile and Assembly.GetTypes?
我正在努力伪造这两行代码:
Assembly asm = Assembly.LoadFile(fileName);
Type[] asmTypes = loggerAssembly.GetTypes();
当我键入 System.Reflection.ShimAssembly
时,没有 ShimAssembly
这样的类型,例如在 System.IO.ShimFile
的情况下,只有 StubAssembly
。
我可以重构代码并使用像 LoadAssemblyAndGetTypes
这样的静态辅助方法来完成它,但这似乎是一个不必要的解决方法。我更喜欢官方解决方案。
如果它只是这样工作:
var shimAsm = System.Reflection.Fakes.ShimAssembly.LoadFile = (fileName) =>
{
return ???
};
var types = shimAsm.GetTypes = () =>
{
return new Type[] { new object() };
};
为什么它适用于 System.IO.File
而不适用于 System.Reflection.Assembly
。这是因为 Assembly
是抽象的 class 吗?
在我的单元测试中,我想检查我的程序集加载器是否正确检查加载的程序集是否包含实现某些接口的类型,以便稍后实例化它们。
我想我找到了答案,但看起来不太好:
@Patrick Tseng - Visual Studio 团队 - 写在 Shim mscorlib and system limitations:
...we DO have a list of type we purposely not allowing them to be
shimmed. Reason being that it could potentially cause recurisvely
calling into your detour delegate from CLR runtime itself. E.g If CLR
runtime uses a type in System.Reflection during runtime and you happen
to detour functions in this type. You might end up causing expected
behavior since runtime behavior will totally be changed.
In short, we don't shim value type, System.Reflection.,
System.Runtime., XamlGeneratedNamespace, and a few other types which
we deem is important and will not shim them.
所以看来我还是需要保留静态辅助方法。
我正在努力伪造这两行代码:
Assembly asm = Assembly.LoadFile(fileName);
Type[] asmTypes = loggerAssembly.GetTypes();
当我键入 System.Reflection.ShimAssembly
时,没有 ShimAssembly
这样的类型,例如在 System.IO.ShimFile
的情况下,只有 StubAssembly
。
我可以重构代码并使用像 LoadAssemblyAndGetTypes
这样的静态辅助方法来完成它,但这似乎是一个不必要的解决方法。我更喜欢官方解决方案。
如果它只是这样工作:
var shimAsm = System.Reflection.Fakes.ShimAssembly.LoadFile = (fileName) =>
{
return ???
};
var types = shimAsm.GetTypes = () =>
{
return new Type[] { new object() };
};
为什么它适用于 System.IO.File
而不适用于 System.Reflection.Assembly
。这是因为 Assembly
是抽象的 class 吗?
在我的单元测试中,我想检查我的程序集加载器是否正确检查加载的程序集是否包含实现某些接口的类型,以便稍后实例化它们。
我想我找到了答案,但看起来不太好:
@Patrick Tseng - Visual Studio 团队 - 写在 Shim mscorlib and system limitations:
...we DO have a list of type we purposely not allowing them to be shimmed. Reason being that it could potentially cause recurisvely calling into your detour delegate from CLR runtime itself. E.g If CLR runtime uses a type in System.Reflection during runtime and you happen to detour functions in this type. You might end up causing expected behavior since runtime behavior will totally be changed.
In short, we don't shim value type, System.Reflection., System.Runtime., XamlGeneratedNamespace, and a few other types which we deem is important and will not shim them.
所以看来我还是需要保留静态辅助方法。