Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Last active December 10, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akimboyko/4495440 to your computer and use it in GitHub Desktop.
Save akimboyko/4495440 to your computer and use it in GitHub Desktop.
Inject dependency into PostSharp aspect
[Serializable]
public class TracingAspectAttribute : OnMethodBoundaryAspect
{
// Question #1: Is there any better way to design aspect
// and to inject dependency into it?
public Type AbstractFactoryType { get; set; }
private ILogger Logger { get; set; }
// Compile time validation.
// Question #2: Better approach to ensure during post-compile time
// that abstract factory could be created at runtime using Activator.CreateInstance
public override bool CompileTimeValidate(MethodBase method)
{
var result = true;
var methodInfo = method as MethodInfo;
// check that AbstractFactoryType contains proper System.Type
if (AbstractFactoryType == null) // check that AbstractFactoryType is provided
{
// break build with following message
Message.Write(methodInfo, SeverityType.Error, "999", "AbstractFactoryType is null");
result = false;
}
else if (!(typeof(IAbstractFactory<ILogger>).IsAssignableFrom(AbstractFactoryType))) // check that AbstractFactoryType is proper type
{
// break build with following message
Message.Write(methodInfo, SeverityType.Error, "999", "Only abstract facory derived from IAbstractFactory<ILogger> allowed");
result = false;
}
else if (AbstractFactoryType.IsAbstract || AbstractFactoryType.IsInterface) // check that instance of AbstractFactoryType could be created
{
// break build with following message
Message.Write(methodInfo, SeverityType.Error, "999", "Only concrete facory derived from IAbstractFactory<ILogger> allowed");
result = false;
}
return result;
}
// Initializes the current aspect at runtime
public override void RuntimeInitialize(MethodBase method)
{
// create instance of Abstract Factory
var abstractFactory = Activator.CreateInstance(AbstractFactoryType);
// create an instance of dependency, only instances of IAbstractFactory<ILogger> could be here
// proven by CompileTimeValidate method
Logger = ((IAbstractFactory<ILogger>)abstractFactory).CreateInstance();
}
// Method executed before the body of methods to which this aspect is applied.
public override void OnEntry(MethodExecutionArgs args)
{
Logger.Log(string.Format("OnEntry {0}.{1}(...)", args.Method.DeclaringType.FullName, args.Method.Name));
}
// Method executed after the body of methods to which this aspect is applied
public override void OnExit(MethodExecutionArgs args)
{
Logger.Log(string.Format("OnExit {0}.{1}(...)", args.Method.DeclaringType.FullName, args.Method.Name));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment