【发布时间】: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());
}
}
【问题讨论】:
-
您的项目中是否安装了
PostSharpNuGet 包?看起来您刚刚安装了PostSharp.Redist包。 -
是的,我在两个类库中使用了这些方面。我只在其中一个中安装了 postsharp 包。现在,当我安装另一个时,问题就解决了。实际上,我认为不会有问题,因为当您将它安装在一个上时它会引用另一个。谢谢。
-
太棒了。我很高兴这有所帮助。我已经将我的建议改写为答案。我可以请你接受吗?
标签: c# .net aop fluentvalidation postsharp