【问题标题】:OnEntry method not working, when using postsharp for AOPOnEntry 方法不起作用,当使用 postsharp 进行 AOP 时
【发布时间】:2021-06-06 14:47:25
【问题描述】:

您好,我正在尝试使用 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());
    }
}

ILSpy

【问题讨论】:

  • 您的项目中是否安装了PostSharp NuGet 包?看起来您刚刚安装了 PostSharp.Redist 包。
  • 是的,我在两个类库中使用了这些方面。我只在其中一个中安装了 postsharp 包。现在,当我安装另一个时,问题就解决了。实际上,我认为不会有问题,因为当您将它安装在一个上时它会引用另一个。谢谢。
  • 太棒了。我很高兴这有所帮助。我已经将我的建议改写为答案。我可以请你接受吗?

标签: c# .net aop fluentvalidation postsharp


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多