spring-projects / spring-net

Spring Framework for .NET
http://www.springframework.net
Apache License 2.0
850 stars 377 forks source link

Extensions methods/properties support for Spring Expressions #221

Open amadare42 opened 2 years ago

amadare42 commented 2 years ago

Hey. I would like to have functionality to add extension methods to objects. So user could define spring (or .net) lambda function for specific type. For example:

var vars = new Dictionary<string, object>{ 
 { "Foo", new Foo() { InternalValue = 2 } }
};
Expressions.RegisterExtensionFunction<Foo>(vars, "SpelExtension", "{|self, arg| $self.InternalValue + $arg}");
Expression.Parse("Foo.SpelExtension(1)").GetValue(null, vars); // result in Foo.InternalValue + 1 -> 3

Expressions.RegisterExtensionFunction<Foo, int>(vars, "CsExtension", (self, arg) => sef.InternalValue + arg);
Expression.Parse("Foo.CsExtension(1)").GetValue(null, vars); // result in Foo.InternalValue + 1 -> 3

Expressions.RegisterExtensionProperty<Foo>(vars, "SpelProp", "{|self| $self.InternalValue + 2}");
Expression.Parse("Foo.SpelProp").GetValue(null, vars); // result in Foo.InternalValue + 2 -> 4

Expressions.RegisterExtensionProperty<Foo>(vars, "CsProp", (self, arg) => sef.InternalValue + 2);
Expression.Parse("Foo.CsProp").GetValue(null, vars); // result in Foo.InternalValue + 2 -> 4

I have a quick and dirty POC that provides this functionality. I can clean it up and create PR. Are maintainers interested in this functionality?

lahma commented 2 years ago

Sorry for the delay. Yes, all contributions are always appreciated!