你可以在不使用属性的情况下在PostSharp中应用方面吗?

Ble*_*ahu 6 aop postsharp

我知道使用Castle Windsor,您可以使用代码而不是将属性应用于类来注册方面(当使用Windsor中的方法拦截作为AOP时).在Postsharp中是否可以相同?这是一个偏好的东西,但更喜欢将方面与接口/对象匹配在一个地方,而不是全部属性.

更新: 好奇我是否可以为与此类似的接口/对象分配方面:

container.Register(
        Component
        .For<IService>()
        .ImplementedBy<Service>()
        .Interceptors(InterceptorReference.ForType<LoggingAspect>()).Anywhere
   );
Run Code Online (Sandbox Code Playgroud)

如果你可以这样做,你可以选择不必在程序集/类/方法上放置属性来应用方面.然后我可以有一个代码文件/类,其中包含哪些方面应用于哪个类/方法/等.

Dus*_*vis 3

是的。可以使用多播(http://www.sharpcrafters.com/blog/post/Day-2-Applying-Aspects-with-Multicasting-Part-1.aspx,http://www.sharpcrafters.com/blog/ post/Day-3-Applying-Aspects-with-Multicasting-Part-2.aspx)或者您可以使用方面提供程序(http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-12-e28093 -Aspect-Providers-e28093-Part-1.aspx ,http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-13-e28093-Aspect-Providers-e28093-Part-2.aspx)。

例子:

    using System;
    using PostSharp.Aspects;
    using PostSharp.Extensibility;

    [assembly: PostSharpInterfaceTest.MyAspect(AttributeTargetTypes = "PostSharpInterfaceTest.Interface1", AttributeInheritance = MulticastInheritance.Multicast)]

    namespace PostSharpInterfaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Example e = new Example();
            Example2 e2 = new Example2();
            e.DoSomething();
            e2.DoSomething();
            Console.ReadKey();
        }
    }

    class Example : Interface1
    {

        public void DoSomething()
        {
            Console.WriteLine("Doing something");
        }
    }

    class Example2 : Interface1
    {

        public void DoSomething()
        {
            Console.WriteLine("Doing something else");
        }
    }

    interface Interface1
    {
        void DoSomething();
    }

    [Serializable]
    class MyAspect : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            Console.WriteLine("Entered " + args.Method.Name);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我建议,如果您对确定哪些类型获得某些方面有复杂的要求,请考虑创建方面提供程序。