How can we get the T4 template to generate code ba

2019-09-05 05:15发布

I'm trying to create a T4 template that will save our developers from creating a lot of boilerplate code that's necessary in our framework. Let's say the developer creates an interface and marks it with our custom attribute. I would like it so that any interface marked with that custom attribute is enhanced by additional methods, which means my T4 template would have to generate partial classes on the fly. However, I would like it so that this automatic generation happens on the fly and seamlessly, preferably when the internal automatic compilation that's used for intellisense happens. You know how when you create a new class in Visual Studio and you switch to another source file and start using that class you didn't have to save or compile it, Intellisense was able to see the new class you created right away? I'd like the same automatic behavior with the code generated from my T4 template. Any thoughts?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-05 05:33

You cannot do what you want to do easily, but here are some options ordered from easiest to most likely what you want (hardest).

  1. Create code snippets

  2. Create a Visual Studio Item Template

  3. Use Castle DynamicProxy to create the extra bits at run time.

  4. Create a separate project to hold the T4 generated classes as described in my answer here

  5. As a pre-step to your project build (modify .csproj file to do this), you can compile the source code from which you want to generated code and then reflect on that, generate the code and then add it to the project before the real compile step. This is what the MSR Orleans project does. You can read their source code here. This is really cool! :-)

查看更多
登录 后发表回答