2

Hi I am trying to use unity interception (I don't want to use unity container). I am able to configure run time but don't know how to configure it from config.

my code:

public interface ICalculator
{
    int Add(int first, int second);

    int Multiply(int first, int second);
}

Behavior:

  internal class LogBehavior : IInterceptionBehavior 
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // My Code
            IMethodReturn result = getNext()(input, getNext);
            return result;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public bool WillExecute {
            get { return true; }
        }
    }

And this is how I am calling it

    public static void Main(string[] args)
    {

        var calculator = new Calculator();
        var calculatorProxy = Intercept.ThroughProxy<ICalculator>(calculator,
          new InterfaceInterceptor(), new[] { new LogBehavior() });
        Console.WriteLine(calculatorProxy.Add(2, 2));

        Console.ReadKey();
    }

This is working. I need to configure this from config file. Please help

4

1 回答 1

0

Without the container, you'll have to do the proxy instanciation yourself. That's the Intercept.ThroughProxy<> call. If you're using another container, you could extend it to read the config and handle it accordingly.

But there's no magic where you can just have .net / unity read the config file and just do new Calculator() and Calculator will be proxied and intercepted with the interceptors defined in the config file. new can't be extended to handle that and as such there will always be some component you'll have to ask for an instance of ICalculator, which will then check whether it needs to be proxied and which interceptors it needs...

Of course, there's an exception to this. If you use weaving (Fody, PostSharp) you can do AOP without using dynamic proxies. And then, you can actually do new Calculator() and it will have it's aspects, not only its core implementation...

于 2014-10-07T11:31:11.340 回答