0

So I've got this boilerplate code that I want to apply to a bunch of properties of certain classes, that is essentially identical for each one. Rather than have to type this same code out again and again for all of these properties, I was wondering if there was any way I could dynamically build these property methods either post-compile or at runtime, by assigning a C# attribute to the property that includes the slight difference for each method (a string) and then finding these properties by reflection.

I'm aware of PostSharp, but I'm looking for something free or open source.

For example, instead of having to do this:

public string Name {
    get { return _member.GetValue( "othername" ); }
    set { _member.SetValue( "othername", value ); }
}

...for each property I have, I just want to say this:

[MapTo( "othername" )]
public string Name { get; set; }

Any thoughts?

0

5 Answers 5

1
  1. You can use Mono.Cecil for dynamic code injection.
  2. You can make these properties as virtual and generate class that overrides these properties and compile new class to assembly where overridden properties will be defined. Then you should create instance of dynamic generated class and used it as defined class.
1
  • Would it be correct to say that Mono.Cecil is only good for rewriting an assembly (.DLL), but that it wouldn't help a lot for manipulating an assembly that's already been loaded into an application domain? Jan 23, 2011 at 10:54
1

You can do something similar using the Unity interception extension.

1

OK, so it probably merits its own answer. I am aware of the following AOP Frameworks for which you won't have to pay:

0

Looks like you are looking for an AOP (Aspect Oriented Programming) like PostSharp.

It allows you to programatically inject code (just like you mentioned) and is very flexible.

2
  • As I said I'm aware of PostSharp, but it's no longer free and requires a $200 license. If you're aware of any viable (free) alternatives, please let me know.
    – devios1
    Jan 21, 2011 at 14:51
  • Ya, I realize that now. I guess frameworks suggested by others are your options then. For example, Mono.Cecil is free.
    – decyclone
    Jan 21, 2011 at 18:08
0

Check out CInject on Codeplex which is an open-source alternative to code injection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.