Search code examples
c#.netaopfluentvalidationpostsharp

OnEntry method not working, when using postsharp for AOP


Hi I am trying to use postsharp aspect for validation. FluentValidationAspect does not working for OnEntry method. (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);
        }
    }
}

It does not go inside the OnEntry method in any way.

ProductManager

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

Test

[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 enter image description here


Solution

  • Each project in which PostSharp aspects are applied needs to have the PostSharp NuGet package installed.