knocte
knocte

Reputation: 17939

Type Providers - Could I generate a type at compilation-time that decorates all methods of a type somehow?

I've read about the great capabilities of Type Providers, such as static-typing when querying JSON documents, so I can imagine that I can create what I have in my mind at the moment, with this technology.

Let's say I want to allow a consumer of my TypeProvider-library Foo a way to create a type Bar, which will have the following pre-condition for each of their methods: check the mutable state of a boolean disposed field, if it's true, throw an ObjectDisposedException.

Would this be possible? How could one define such an implementation of this high-level type creator?

Upvotes: 10

Views: 187

Answers (1)

Phillip Trelford
Phillip Trelford

Reputation: 6543

A couple of years back Keith Battocchi published a project called ILBuilder. Among other things ILBuilder contains a method type provider in ILBuilder.fs that provides methods for types in mscorlib, e.g.

MethodProvider.Methods.System.Console.``WriteLine : string*obj->unit`

It is possible you could use this as a starting point for a type provider that wraps classes from another assembly and provides methods.

Another option might be to consider Ross McKinlay's Mixin Type Provider that (ab)uses F#'s Type Provider mechanism to provide meta-programming capabilities.

Yet another option might be to use PostSharp, Fody etc. to do IL weaving, or code generation via reflection to build proxy classes.

That said probably the lowest friction solution would be to create a function that checks for disposal and manually add it to each member.

Upvotes: 7

Related Questions