First, I never used Unity before...
I want to introduce Tracing / Logging to our project through unity interception.
The project is considerably big (~30000 files). The goal is to trace performance / execution period every time we try to call outside service. Regrettably I cannot use any other library.
To get familiar with how this concept is going to work, I built a small program that I found on MSDN; however my interception with log attribute still does not fire. I am sure I am missing some configuration or / and initialization.
I appreciate any help.
Here is my Main program:
namespace calc
{
class Program
{
static void Main(string[] args)
{
try
{
var t = new calc.Calculator.Calculator().Sub(5, 8);
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
}
}
Here is Calculator class:
namespace calc.Calculator
{
public interface ICalculator
{
Int32 Sum(Int32 x, Int32 y);
Int32 Sub(Int32 x, Int32 y);
}
public class Calculator : ICalculator
{
public Int32 Sum(Int32 x, Int32 y)
{
return x + y;
}
[NonNegativeCallHandler] // Intercept this method and run tracing on it
public Int32 Sub(Int32 x, Int32 y)
{
return x - y;
}
}
}
Here is my CallHandler:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace calc.Tracing
{
public class NonNegativeCallHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input,
GetNextHandlerDelegate getNext)
{
// Perform the operation
var methodReturn = getNext().Invoke(input, getNext);
// Method failed, go ahead
if (methodReturn.Exception != null)
return methodReturn;
// If the result is negative, then throw an exception
var result = (Int32)methodReturn.ReturnValue;
if (result < 0)
{
var exception = new ArgumentException("...");
var response = input.CreateExceptionMethodReturn(exception);
// Return exception instead of original return value
return response;
}
return methodReturn;
}
public int Order { get; set; }
}
}
And Finally
*Here is my Attribute definition:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.Unity;
namespace calc.Tracing
{
public class NonNegativeCallHandlerAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new NonNegativeCallHandler();
}
}
}
What else exactly I need to add, and where (config file or inside constructor, etc..) in order for this code to work.