简体   繁体   中英

Visual studio AfterBuild Task that generates code

I'd like to create an AfterBuild Task that generates code in a Visual Studio project. The problem is that since it is an AfterBuild Task, the generated code won't get compiled.

I need it to be an AfterBuild Task because I load the output assembly of the build and inspect it using reflection in order to generate the code.

Is there a way that I can compile the generated code after the AfterBuild Task?

Thanks.

It is possible to compile C# code at runtime using the CSharpCodeProvider Class, look at this article , it is well explained. Although by the sound of it looks like you want to change (eg to weave) your library by injecting the code you are compiling in your AfterBuild task event.

If that is the case the only way to achieve what you want to do is to use an AOP (Aspect Oriented Programming) framework like PostSharp or Mono.Cecil. What they do is generating IL (Intermediate Language) and injecting at run-time or at compile time into your program.

In this answer are discussed a few AOP solutions for .NET.

EDIT:

To compile c# project (*.csproj) programmatically there are specific classes in the .NET framwork. Look at the Microsoft.Build.Evaluation namespace.

However this snippet should work for you. Try it in your Task and you should be able to fire another compilation process from your code.

      const string projectPath = @"your csproj path";
      var collection = new Microsoft.Build.Evaluation.ProjectCollection {DefaultToolsVersion = "4.0"};


      collection.RegisterLogger(new ConsoleLogger());
      collection.LoadProject(projectPath);

      var project = new Microsoft.Build.Evaluation.Project(collection);

      if (!project.Build())
      {
         //Error
      }

hope it helps.

CSC does the trick. Inside my vcproj, I included:

  <Target Name="AfterBuild">
        <MyGenerateCodeTask />
        <CSC
              Sources="@(Compile)"
              References="@(Reference)"
              AdditionalLibPaths="$(OutputPath)"
              OutputAssembly="$(TargetName)$(TargetExt)"
              EmitDebugInformation="true" >
        </CSC>
  </Target>

To make sure CSC finds all the required references, add the following:

<Reference Include="$(OutputPath)*.dll"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM