kzu / InjectModuleInitializer

Console program and nuget package to inject a module initializer method into a built .NET assembly
http://einaregilsson.com/module-initializers-in-csharp/
MIT License
97 stars 32 forks source link

InjectModuleInitializer.exe for .NET 4.5 or greater #18

Open GR-C opened 5 years ago

GR-C commented 5 years ago

Currently the InjectModuleInitializer.exe needs .NET 3.5 to run. Could you create a version that targets the .NET framework 4.5 or greater?

mford1 commented 5 years ago

Creating a .config in the same folder as the executable with a supportedRuntime entry should work.

stevebaxter commented 3 years ago

We have the same problem - our builds are failing on Jenkins because .NET 3.5 isn't installed on the build agents. This also makes it a little bit difficult to create the .config file, as Nuget is managing the packages.

stevebaxter commented 2 years ago

For anyone who comes hunting for a solution to this, I have a workaround. The symptom is that your build will fail with something like:

error MSB3073: The command ""somepath\.nuget\packages\injectmoduleinitializer\2.0.3\tools\net35\InjectModuleInitializer.exe" /k:".StrongNameKey.snk" "MyDLL.dll"" exited with code -2146232576

The solution is to add a .config file to InjectModuleInitializer.exe as part of the build process, so whenever Nuget fetches a new version we add the config file alongside it. To do this:

  1. Create a file called InjectModuleInitializer.exe.config with this content:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <startup>
      <supportedRuntime version="v2.0.50727"/>
      <supportedRuntime version="v4.0"/>
    </startup>
    </configuration>
  2. Add this to your project to modify <PackageReference> for InjectModuleInitializer:
    <ItemGroup>
    <PackageReference Include="InjectModuleInitializer" Version="2.0.3" GeneratePathProperty="true">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    </ItemGroup>
    <!-- Make InjectModuleInitializer compatible with .NET 4.x -->
    <Target Name="FixInjectModuleInitializer" BeforeTargets="InjectModuleInitializer">
    <Copy SourceFiles="$(ProjectDir)\InjectModuleInitializer.exe.config"
          DestinationFolder="$(PkgInjectModuleInitializer)\tools\net35" />
    </Target>

    Note the GeneratePathProperty="true" that's been added.

Hey presto, the config file will be copied alongside InjectModuleInitializer.exe just before it is used and it will run under .NET 4.