PostSharp Resolution Aspect Type

We are using dependency injection with and IoC (Unity), and now I want to make an aspect with PostSharp, which will basically register the input / output of the method. My problem is that my registrar is configured and registered in the unity container. What should be the best approach for solving a journal in my aspect?

Note. Using interceptors in unity is not an option. I want this to work without a class, allowed through unity.

+4
source share
2 answers

use an aspect that inherits from OnMethodBoundaryAspect, and in OnMethodEntry / OnMethodExit just make a call from your aspect to Unity to enable your registrar, and then register.

Apply aspect anyway (class, method, or even assembly level)

[Serializable] [MulticastAttributeUsage(MulticastTargets.Method, Inheritance=MulticastInheritance.Strict)] public class LogAspect : OnMethodBoundaryAspect { public override void OnEntry(MethodExecutionArgs args) { var Logger = Unity.Resolve<T>(); Logger.Write(args.Method.Name + " enter"); } public override void OnExit(MethodExecutionArgs args) { var Logger = Unity.Resolve<T>(); Logger.Write(args.Method.Name + " exit"); } } 

To get the union container, I would use a service locator pattern.

 public class iocServiceLocator { private static readonly IUnityContainer _container; static iocServiceLocator() { _container = new UnityContainer(); } public static void Initialize() { InitializeBootStrap(); } private static void InitializeBootStrap() { //Register types here } public static T Get<T>() { return _container.Resolve<T>(); } public static T Get<T>(string key) { return _container.Resolve<T>(key); } } 
+2
source

without service locator

add static property logger to your Aspect class

 public class LogAspect : OnMethodBoundaryAspect { /// <summary> /// Gets or sets the logger. /// </summary> public static ILogger logger { get; set; } 

set the registrar variable in the application initialization method with your ILogger class and exclude all methods before this initialization using AttributeExclude.

  [LogAspect(AttributeExclude = true)] protected void Application_Start() { _windsorContainer = new WindsorContainer(); ApplicationDependencyInstaller.RegisterLoggingFacility(_windsorContainer); LogAspect.logger = _windsorContainer.Resolve<ILogger>(); 
0
source

All Articles