If you are trying to inject the lambda expression, rather than the result of the lambda expression, you have quite a few imperfect options. Here are just a few; I'm sure that there are more.
Autofac
The Autofac wiki on Google Project Hosting documents four ways of injecting properties. Three of them appear to use constant or default values--you mentioned one of these methods.
The final seems to give the developer a bit more control over properties. It uses the OnActivating event, during which you have a few options. You could:
- Set the property and hope it sticks.
- If the property lacks an accessible setter, you could use reflection to set it, or its backing property (by default, m_PropertyName for a property named PropertyName, if I recall correctly).
- Wrap the instance in a proxy, as they put it: see Polymorphism below.
Polymorphism
Let ClassA
contain the property to be modified, Prop1
. Create a new class ClassB
that extends ClassA
. If Prop1
has a virtual
modifier, you can override it. Otherwise, use the new
modifier to create a similar property in ClassB
containing your dynamic code.
In the case of an override, you will need to instantiate ClassB
in place of ClassA
. This will not work if the framework creates its own instances of ClassA
, but as long as you create your own instances of ClassB
and pass them to the framework, you should be good to go.
If you are using a new property, in addition to instantiating ClassB
, you also have to ensure that whenever you access the new property, the object is cast to ClassB
or a descendant type. This generally will not work if another framework is designed to use ClassA
, since it will always operate on type ClassA
, not ClassB
, regardless of your casting.
Bytecode Manipulation
This is nasty stuff, but it will do exactly what you want. C# generally compiles to an assembly/bytecode language called CIL. Microsoft's variant is MSIL, but it's pretty much identical to generic CIL.
I've always used Mono.Cecil for CLI/CLR (.NET, Mono) bytecode manipulation. It seems to work flawlessly, and it's quite nice once you get the hang of it. However, you have to know two things:
- How to use CIL
- How to use Mono.Cecil
The first one isn't that bad. A few Wikipedia pages with detailed tables are all that you need, provided that you have sufficient experience with CLI. If you think CLI stands for nothing other than "command line interface", then you might run into difficulty.
Mono.Cecil, on the other hand, lacked any form of proper documentation as of about a year ago (2012). The learning curve was impossibly steep. I had a miserable few days trying to figure it out. It's amazing when it works, though.