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

问题描述 投票:5回答:1

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

我有以下程序(我签名/强名)。它告诉Castle DynamicProxy(我正在使用Castle.Core NuGet包的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) { }
}

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

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

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


P.S。:我知道我可以通过公开将InterfaceProxyBase公开并用[EditorBrowsable(Never)]隐藏它来解决这个问题,但是我真的不想让这个内部类型公开,如果我不需要的话。

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

.net .net-core castle-dynamicproxy bcl internalsvisibleto
1个回答
4
投票

你应该为InternalsVisibleTo设置DynamicProxyGenAssembly2

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

DynamicProxyGenAssembly2是由Castle.DynamicProxy建造的临时集会。此程序集包含继承自InterfaceProxyBase的生成代理类型。这就是为什么DynamicProxyGenAssembly2应该可以访问InterfaceProxyBase类型。可能的选择是添加InternalsVisibleTo属性或使InterfaceProxyBase公开。

© www.soinside.com 2019 - 2024. All rights reserved.