Postsharp Newbie-为什么args.Instance为null? [英] Postsharp Newbie - Why is args.Instance null?

查看:89
本文介绍了Postsharp Newbie-为什么args.Instance为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PostSharp的新功能---我现在正在试用NuGet版本,并且试图了解agrs.Instance值为null的AuthoriseAttribute OnEntry方法中的wny.我正在尝试实现依赖于对象值的授权,例如已存档的客户无法提高信用额度.我正在其他特定于规则的类中实现规则.

New to PostSharp --- I'm trying out the NuGet version now and I'm trying to understand wny in the AuthoriseAttribute OnEntry method that the agrs.Instance value is null. I'm trying to implement authorsation that depends on the values of the object e.g. A customer who's been archived can't have a credit limit raised. I'm implementing the rules within other classes specific to the rules.

public class Program
{
    static void Main(string[] args)
    {
        var c = new Customer();
        c.RaiseCreditLimit(100000);
        c.Error(00); 
    }
}

public class Customer
{
    [AuthorizeActivity]
    public void RaiseCreditLimit(int newValue)
    {
    }

    [AuthorizeActivity]
    public void Error(int newValue)
    {

    }
}

[Serializable]
public class AuthorizeActivityAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        //
        //Why is args.Instance null???????????
        //
        if (args.Method.Name == "RaiseCreditLimit")
        {
            Debug.WriteLine(args.Method.Name + " started");
        }
        else
        {
            throw new Exception("Crap");
        }
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        Debug.WriteLine(args.Method.Name + " finished");
    }
}

推荐答案

答案是因为您没有在方面使用它.这是一个优化.如果您在方面中使用它,那么它将被设置.更改外观以使用实例,它将存在.

The answer is because you're not using it in your aspect. It's an optimization. If you use it in the aspect then it will be set. Change your aspect to consume instance and it will be there.

public override void OnEntry(MethodExecutionArgs args)
        {
            //
            //Why is args.Instance null???????????
            //
            if (args.Method.Name == "RaiseCreditLimit")
            {
                Debug.WriteLine(args.Instance.GetType().Name);
                Debug.WriteLine(args.Method.Name + " started");
            }
            else
            {
                throw new Exception("Crap");
            }
        }

有关更多信息,请查看本文,以了解PostSharp还可以做什么来优化代码

For more info check out this article to see what else PostSharp does to optimize code http://programmersunlimited.wordpress.com/2011/03/23/postsharp-weaving-community-vs-professional-reasons-to-get-a-professional-license/

这篇关于Postsharp Newbie-为什么args.Instance为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆