I found a lot of examples on how to implement Unity interception with configuration files, but no concise examples of how to configure it with verbose code. Hopefully someone else will find this useful too.
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using System;
namespace UnityExample
{
class Program
{
private static IUnityContainer unityContainer;
static void Main(string[] args)
{
unityContainer = new UnityContainer();
unityContainer.AddNewExtension<interception>();
unityContainer.Configure<interception>()
.SetInterceptorFor<iauthenticationservice>(new InterfaceInterceptor());
}
}
public class LogExceptionsHandler : ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Console.WriteLine("Before method Invocation happened");
var methodReturn = getNext().Invoke(input, getNext);
if (methodReturn.Exception != null)
{
Console.WriteLine("Add some real logging here");
}
else
{
Console.WriteLine
("To Rethrow, or not to rethrow, that is the question.");
}
return methodReturn;
}
}
public class LogExceptionsAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
{
return new LogExceptionsHandler();
}
}
public interface IAuthenticationService
{
[LogExceptions]
bool isAuthenticated(string userName, string password);
}
}