注册Unity拦截器时出现ResolutionFailedException

本文关键字:ResolutionFailedException Unity 注册 | 更新日期: 2023-09-27 18:25:40

我有这段代码。

class Program
{
    static void Main(string[] args)
    {
        IUnityContainer container = new UnityContainer();
        container.AddNewExtension<Interception>();
        container.RegisterType<ITestInterception, TestInterception>(new TransientLifetimeManager(),
                                                 new Interceptor<InterfaceInterceptor>(),
                                                 new InterceptionBehavior<PolicyInjectionBehavior>());

        container.Configure<Interception>()
                 .AddPolicy("MyPolicy")
                 .AddMatchingRule(new MemberNameMatchingRule("Test"))
                 .AddCallHandler<FaultHandler>();
        try
        {
            var tester = container.Resolve<ITestInterception>();
            tester.Test();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.GetType() + "'n'n");
        }
        Console.ReadKey();
    }
}
class AlwaysMatchingRule : IMatchingRule
{
    public bool Matches(MethodBase member)
    {
        return true;
    }
}
interface ITestInterception
{
    void Test();
}
class TestInterception : ITestInterception
{
    public void Test()
    {
        throw new ArgumentNullException("Null");
    }
}
class FaultHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        Console.WriteLine("Invoke called");
        IMethodReturn result = getNext()(input, getNext);
        Exception e = result.Exception;
        if (e == null)
            return result;
        return input.CreateExceptionMethodReturn(new InvalidOperationException("In interceptor", e));
    }
    public int Order { get; set; }
}

当它运行时,我有ResolutionFailedException。

解析依赖关系失败,键入="TestUnity.ITestInterception",name="(none)"。发生异常while:解析时。异常为:TypeLoadException-类型'动态模块.ns.Wrapped_ITestInterception_0e954c5db37c4c4ebf99acaee12e93f7'来自程序集的Unity_ILEmit_InterfaceProxies,版本=0.0.0.0,

你能给我解释一下如何解决这个问题吗?

注册Unity拦截器时出现ResolutionFailedException

InnerException消息说明了一切:

程序集"Unity_ILEmit_InterfaceProxies,Version=0.0.0.0,Culture=neutral,PublicKeyToken=null"中的类型"DynamicModule.ns.Wrapped_ITestInterception_c8a0c8bf8a3d48a5b7f85924fab5711f"正在尝试实现不可访问的接口。

您需要公开您的界面:

public interface ITestInterception
{
    void Test();
}

@Roelf答案的替代方案是允许调用程序集访问内部接口/对象:

在具有Unity配置的项目中,在Properties下添加:

[assembly: InternalsVisibleTo("Unity_ILEmit_InterfaceProxies")]
相关文章:
  • 没有找到相关文章