哪个`[InternalsVisibleTo]`用于.NET Framework和.NET Standard/Core框架程序集?

sta*_*ica 5 .net castle-dynamicproxy internalsvisibleto base-class-library .net-core

我遇到了跨装配/朋友装配类型可见性的问题.

我有以下程序(我签名/强名).它告诉Castle DynamicProxy(我使用的是Castle.CoreNuGet包的4.2.1版)为我的界面创建一个代理IFoo.我还指定我internal class 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) { }
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

所以,显然我需要一个[assembly: InternalsVisibleTo]框架自己的程序集/程序集的属性.我的程序(实际上是一个类库)同时针对.NET 4.5和.NET Standard 1.3.

[assembly: InternalsVisibleTo]我需要哪些属性(包括精确的公钥)才能使我的代码适用于上述平台/目标?


PS:我知道我可以通过InterfaceProxyBase公开和隐藏它来避免这个问题[EditorBrowsable(Never)],但是我真的不想让这个内部类型公开,如果我不需要的话.

PPS:如果将内部公开给框架集会是一个非常糟糕的想法,安全方面,请让我知道,然后我会高兴地重新考虑我的方法.

Cod*_*ler 5

你应该设置InternalsVisibleToDynamicProxyGenAssembly2

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
Run Code Online (Sandbox Code Playgroud)

DynamicProxyGenAssembly2是由Castle.DynamicProxy. 此程序集包含从您的InterfaceProxyBase. 这就是为什么DynamicProxyGenAssembly2应该有权访问InterfaceProxyBase类型。可能的选项是添加InternalsVisibleTo属性或InterfaceProxyBase公开。