Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miklund/df7bf1187c746b0d624c to your computer and use it in GitHub Desktop.
Save miklund/df7bf1187c746b0d624c to your computer and use it in GitHub Desktop.
2009-10-30 AOP in .NET with Unity Interception Model
# Title: AOP in .NET with Unity Interception Model
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2009/10/30/aop-in-net-with-unity-interception-model.html
public class AnyMatchingRule : IMatchingRule
{
public bool Matches(MethodBase member)
{
return true;
}
}
public class Container : UnityContainer
{
public void Configure()
{
/* Register types into the container */
RegisterType<IDataFactory, StubDataFactory>();
RegisterType<IDataAccess<Customer>, CustomerDataAccess>();
/* Register our matching rule and call handler */
RegisterType<IMatchingRule, AnyMatchingRule>("AnyMatchingRule");
RegisterType<ICallHandler, LogCallHandler>("LogCallHandler");
/* Create a new policy and reference the matching rule and call handler by name */
AddNewExtension<Interception>();
Configure<Interception>().AddPolicy("LogPolicy")
.AddMatchingRule("AnyMatchingRule")
.AddCallHandler("LogCallHandler");
/* Make IDataAccess interface elegible for interception */
Configure<Interception>().SetInterceptorFor(typeof(IDataAccess<>), new TransparentProxyInterceptor());
}
}
public Customer GetById(int id)
{
System.Diagnostics.Debug.WriteLine("CustomerDataAccess.GetById(" + id + ")"); // Noise
Customer result = null;
using (var connection = dataFactory.OpenConnection())
{
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Customer WHERE id=" + id; // Beware of SQL injection
var reader = command.ExecuteReader();
result = reader.GetCustomer();
}
System.Diagnostics.Debug.WriteLine("CustomerDataAccess.GetById(" + id + ") -> " + result);
return result;
}
var repository = Container.Instance.Resolve<CustomerRepository>();
var customer = repository.GetCustomerById(1);
var container = new Container();
container.Configure();
var dataAccess = container.Resolve<IDataAccess<Customer>>();
dataAccess.GetById(1);
public class LogCallHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
string className = input.MethodBase.DeclaringType.Name;
string methodName = input.MethodBase.Name;
string arguments = GetArgumentList(input.Arguments);
/* CustomerDataAccess.GetById(123) */
string preMethodMessage = string.Format("{0}.{1}({2})", className, methodName, arguments);
System.Diagnostics.Debug.WriteLine(preMethodMessage);
/* Call the method that was intercepted */
IMethodReturn msg = getNext()(input, getNext);
string postMethodMessage = string.Format("{0}.{1}() -> {2}", className, methodName, msg.ReturnValue);
System.Diagnostics.Debug.WriteLine(postMethodMessage);
return msg;
}
public int Order { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment