N
Niels Ull
Hi!
I'm using .Net 2.0 and C#, and I'm trying to generate code for build time
AOP. But I cannot find out how to generate an anonymous delegate.
E.g. generating code like this:
class MyClassWrapper
{
public static void StaticMethod(int param1, int param2)
{
DbContext.DoInTransaction( delegate { MyClass.StaticMethod(param1,
param2} );
}
}
Background: This is based on having MyClass
class MyClass
{
[TransactionRequired]
public static void StaticMethod(int param1, int param2) {...}
}
But apparently I cannot generate this with the CodeDOM?
My best approach so far is to do a C# roundtrip - e.g.
private CodeExpression GetAnonymousDelegateExpression(CodeStatement statementToWrap)
{
CodeExpression delegateExpression;
CSharpCodeProvider csc = new CSharpCodeProvider();
StringWriter sw = new StringWriter();
csc.GenerateCodeFromStatement(statementToWrap, sw, new CodeGeneratorOptions());
delegateExpression = new CodeSnippetExpression("delegate {" + sw.ToString()
+ "}");
return delegateExpression;
}
but that seems very clunky? Any ideas?
Having to generate my own randomly-named method will be a bit complex since
I have to handle capturing outer variables
I'm using .Net 2.0 and C#, and I'm trying to generate code for build time
AOP. But I cannot find out how to generate an anonymous delegate.
E.g. generating code like this:
class MyClassWrapper
{
public static void StaticMethod(int param1, int param2)
{
DbContext.DoInTransaction( delegate { MyClass.StaticMethod(param1,
param2} );
}
}
Background: This is based on having MyClass
class MyClass
{
[TransactionRequired]
public static void StaticMethod(int param1, int param2) {...}
}
But apparently I cannot generate this with the CodeDOM?
My best approach so far is to do a C# roundtrip - e.g.
private CodeExpression GetAnonymousDelegateExpression(CodeStatement statementToWrap)
{
CodeExpression delegateExpression;
CSharpCodeProvider csc = new CSharpCodeProvider();
StringWriter sw = new StringWriter();
csc.GenerateCodeFromStatement(statementToWrap, sw, new CodeGeneratorOptions());
delegateExpression = new CodeSnippetExpression("delegate {" + sw.ToString()
+ "}");
return delegateExpression;
}
but that seems very clunky? Any ideas?
Having to generate my own randomly-named method will be a bit complex since
I have to handle capturing outer variables