首页 > 解决方案 > OnEntry 方法不起作用,当使用 postsharp 进行 AOP 时

问题描述

嗨,我正在尝试使用 postsharp 方面进行验证。FluentValidationAspect不适用于 OnEntry 方法。(postsharp v6.9.6)

FluentValidationAspect

[Serializable]
public class FluentValidationAspect : OnMethodBoundaryAspect
{
    private Type _validatorType;
    public FluentValidationAspect(Type validatorType)
    {
        _validatorType = validatorType;
    }
    public override void OnEntry(MethodExecutionArgs args)
    {
        var validator = (IValidator)Activator.CreateInstance(_validatorType);

        var entityType = _validatorType.BaseType.GetGenericArguments()[0];
        var entities = args.Arguments.Where(o => o.GetType() == entityType);

        foreach (var entity in entities)
        {
            ValidatorTool.FluentValidate(validator, entity);
        }
    }
}

它不会以任何方式进入 OnEntry 方法。

产品经理

    [FluentValidationAspect(typeof(ProductValidator))]
    public Product Add(Product product)
    {
        return _productDal.Add(product);
    }

测试

[TestClass]
public class ProductManagerTests
{
    [ExpectedException(typeof(ValidationException))]
    [TestMethod]
    public void Product_Validation_Check()
    {
        Mock<IProductDal> mock = new Mock<IProductDal>();
        ProductManager productManager = new ProductManager(mock.Object);

        productManager.Add(new Product());
    }
}

间谍 在此处输入图像描述

标签: c#.netaopfluentvalidationpostsharp

解决方案


每个应用 PostSharp 方面的项目都需要PostSharp安装 NuGet 包。


推荐阅读