lomomike lomomike - 1 month ago 17
C# Question

ResolutionFailedException when register a Unity interceptor

I have this code.

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; }
}


When it runs, I has ResolutionFailedException.


Resolution of the dependency failed, type =
"TestUnity.ITestInterception", name = "(none)". Exception occurred
while: while resolving. Exception is: TypeLoadException - Type
'DynamicModule.ns.Wrapped_ITestInterception_0e954c5db37c4c4ebf99acaee12e93f7'
from assembly 'Unity_ILEmit_InterfaceProxies, Version=0.0.0.0,


Can you explain me how to solve this problem?

Answer

The InnerException message says it all:

Type 'DynamicModule.ns.Wrapped_ITestInterception_c8a0c8bf8a3d48a5b7f85924fab5711f' from assembly 'Unity_ILEmit_InterfaceProxies, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

You need to make your interface public:

public interface ITestInterception
{
    void Test();
}