There might be times where-in you will have to write custom matching rules and the corresponding handlers to achieving auditing. Unity Application Block provides that flexibility to achieve this. Below is the code which will help to to do
Matching Rule:
public class MethodMatchingRule : IMatchingRule
{
{
string _MethodName = string.Empty;
public MethodMatchingRule(string MethodName)
{
_MethodName = MethodName;
}
public MethodMatchingRule()
{
}
public bool Matches(MethodBase member)
{
return member.Name == _MethodName;
}
}
Custom Handler:
public class DynamicHandler : ICallHandler
{
public int Order { get; set; }
public DynamicHandler()
{
}
public DynamicHandler(int order)
{
this.Order = order;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Console.Write("DynamicHandler, ");
//We can write to DB or file or anything
string name = input.MethodBase.Name;
Type objType = input.MethodBase.DeclaringType;
IMethodReturn result = getNext()(input, getNext);
//Console.Write("By Dynamic Handler ");
//We can write to DB or file or anything
return result;
}
}
Code to create Objects:
public static TInterface GetFactory() where TObject : TInterface
{
container.AddNewExtension();
container.RegisterType().Configure().SetInterceptorFor(
new InterfaceInterceptor());
container.Configure().AddPolicy("Test").AddMatchingRule(new MethodMatchingRule("Write")).AddCallHandler(new DynamicHandler());
var logger = container.Resolve();
return (TInterface)logger;
}
Code to execute:
ILogger logger = InterfaceInterceptorProxy.GetFactory<ILogger, Logger>();
logger.Write("World.");
{
public int Order { get; set; }
public DynamicHandler()
{
}
public DynamicHandler(int order)
{
this.Order = order;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Console.Write("DynamicHandler, ");
//We can write to DB or file or anything
string name = input.MethodBase.Name;
Type objType = input.MethodBase.DeclaringType;
IMethodReturn result = getNext()(input, getNext);
//Console.Write("By Dynamic Handler ");
//We can write to DB or file or anything
return result;
}
}
Code to create Objects:
public static TInterface GetFactory
{
container.AddNewExtension
container.RegisterType
new InterfaceInterceptor());
container.Configure
var logger = container.Resolve
return (TInterface)logger;
}
Code to execute:
ILogger logger = InterfaceInterceptorProxy.GetFactory<ILogger, Logger>();
logger.Write("World.");
No comments:
Post a Comment