Unity interception doesn't work as expected

343 views Asked by At

I use unity as my aop framework, but it doesn't work as expected. Please check my code below.

container.RegisterType<IPerson, Person>(new Interceptor<TransparentProxyInterceptor>(),
    new InterceptionBehavior<LoggingInterceptionBehavior>(), 
    new InjectionConstructor(container.Resolve<IPlay>(), container.Resolve<IEat>()));

var person = container.Resolve<IPerson>();
person.Play();
person.Eat();
((IAnimal)person).Sleep();
Console.Read();

public IMethodReturn Invoke(IMethodInvocation input,
       GetNextInterceptionBehaviorDelegate getNext)
{
    Console.WriteLine(string.Format("Invoking method {0} begin", input.MethodBase));
    var result = getNext()(input, getNext);
    if (result.Exception != null)
    {
        Console.WriteLine("{0} throws exception", input.MethodBase);
    }
    else
    {
        Console.WriteLine(string.Format("Invoking method {0} end", input.MethodBase));
    }
    return result;
}

When container.Resolve() and ((IAnimal)person) run, the behavior also executed, and print out

Invoking method System.Type GetType() begin

Invoking method System.Type GetType() end

I want the log only execute when I call method explicitly. how to prevent it?

0

There are 0 answers