我遇到了跨程序集/友元程序集类型可见性问题。
我有以下程序(我签名/强名称)。它告诉 CaSTLe DynamicProxy(我使用的是 CaSTLe.Core
NuGet 包的 4.2.1 版本)为我的接口(interface) IFoo
创建代理。我还指定我的内部类 InterfaceProxyBase
应该是代理类型的基类。
DynamicProxy 然后使用 System.Reflection.Emit
创建代理类型。但显然,System.Reflection.Emit.TypeBuilder
无法访问 InterfaceProxyBase
。
// [assembly: InternalsVisibleTo("?")]
// ^^^
// What do I need here for my program to work both on the .NET Framework 4.5+
// and on .NET Core / .NET Standard 1.3+?
using Castle.DynamicProxy;
class Program
{
static void Main()
{
var generator = new ProxyGenerator();
var options = new ProxyGenerationOptions
{
BaseTypeForInterfaceProxy = typeof(InterfaceProxyBase) // <--
};
var proxy = generator.CreateInterfaceProxyWithoutTarget(
typeof(IFoo),
options,
new Interceptor());
}
}
public interface IFoo { }
internal abstract class InterfaceProxyBase { }
internal sealed class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation) { }
}
<小时/>
Unhandled Exception: System.TypeLoadException: Access is denied: 'InterfaceProxyBase'.
at System.Reflection.Emit.TypeBuilder.TermCreateClass(RuntimeModule module, Int32 tk, ObjectHandleOnStack type)
...
at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithoutTarget(Type interfaceToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors)
at Program.Main() in Program.cs
所以,显然我需要框架自己的程序集的 [assemble: InternalsVisibleTo]
属性。我的程序(实际上是一个类库)同时面向 .NET 4.5 和 .NET Standard 1.3。
我需要哪些[程序集:InternalsVisibleTo]
属性(包括精确的公钥)才能使我的代码适用于上述平台/目标?
P.S.:我知道我可以通过将 InterfaceProxyBase
公开并使用 [EditorBrowsable(Never)]
隐藏它来规避这个问题,但我真的不知道如果不需要的话,我不想公开这个内部类型。
P.P.S.:如果从安全角度来看,将内部结构公开给框架程序集是一个非常糟糕的主意,请让我知道,那么我会很乐意重新考虑我的方法。
最佳答案
您应该为DynamicProxyGenAssembly2
设置InternalsVisibleTo
:
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
DynamicProxyGenAssembly2
是由 CaSTLe.DynamicProxy
构建的临时程序集。此程序集包含从您的InterfaceProxyBase 继承的生成的代理类型。这就是为什么 DynamicProxyGenAssembly2
应该有权访问 InterfaceProxyBase
类型。可能的选项是添加 InternalsVisibleTo
属性或将 InterfaceProxyBase
公开。
关于.net - 哪个 `[InternalsVisibleTo]` 用于 .NET Framework 和 .NET Standard/Core 框架程序集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47761193/