Search code examples
c#dependency-injectionaoppostsharp

PostSharp aspect resolving type


We are using dependency injection with and IoC (Unity) and now I want to make an aspect with PostSharp that would basically log enter/exit of a method. My problem is that my logger is configured and registered in the unity container. What should be the best approach to resolve the logger in my aspect?

Note: Using interceptors in unity is not an option. I want this to work without the class is resolved through unity.


Solution

  • use an aspect that inherits from the OnMethodBoundaryAspect and in the OnMethodEntry/OnMethodExit just make a call from your aspect to Unity to resolve your logger then do you logging.

    Apply the aspect anyway you want (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 your unity 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);
            }
    
    
        }