开发者

PostSharp aspect resolving type

开发者 https://www.devze.com 2023-02-27 02:19 出处:网络
We are using dependency inje开发者_如何学Goction 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 c

We are using dependency inje开发者_如何学Goction 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.


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);
        }


    }


without a service locator

add a static property logger in your class Aspect

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

set logger variable in your application init method with your ILogger class and exclude all methods before this initialization with AttributeExclude.

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

精彩评论

暂无评论...
验证码 换一张
取 消