zzzprojects / System.Linq.Dynamic.Core

The .NET Standard / .NET Core version from the System Linq Dynamic functionality.
https://dynamic-linq.net/
Apache License 2.0
1.57k stars 228 forks source link

The `DynamicLinqType` attribute can not be added to interfaces. #745

Closed Magnus12 closed 1 year ago

Magnus12 commented 1 year ago

The DynamicLinqType attribute can not be added to interfaces. If I have a field in a class that is of type interface:

private readonly IExternalMethod externalMethod;

Interface and implementation:

    public interface IExternalMethod 
    {
        int Run();
    }

    [DynamicLinqType]
    public class ExternalMethod : IExternalMethod
    {
        public int Run() => 1;
    }

Trying to run functions on that with dynamic linq does not work even in the implementing class of the interface has the DynamicLinqType attribute.

StefH commented 1 year ago

@Magnus12 I can remove the restriction for only using it on classes and structs.

StefH commented 1 year ago

@Magnus12

I've update the attribute and created this this test:

[DynamicLinqType]
    public interface ICustomInterfaceWithMethodWithDynamicLinqTypeAttribute
    {
        int GetAge(int x);
    }

    public class CustomClassImplementingInterface : ICustomInterfaceWithMethodWithDynamicLinqTypeAttribute
    {
        public int GetAge(int x) => x;
    }

        // Arrange
        var context = new CustomClassImplementingInterface();
        var expression = $"{nameof(ICustomInterfaceWithMethodWithDynamicLinqTypeAttribute.GetAge)}(10)";

        // Act
        var lambdaExpression = DynamicExpressionParser.ParseLambda(typeof(ICustomInterfaceWithMethodWithDynamicLinqTypeAttribute), null, expression);
        var del = lambdaExpression.Compile();
        var result = (int?)del.DynamicInvoke(context);

        // Assert
        result.Should().Be(10);

This is what you need?

(https://github.com/zzzprojects/System.Linq.Dynamic.Core/pull/750)

Magnus12 commented 1 year ago

Great! Thank you!