mardi 20 août 2019

Create assembly that when referenced it prevents a program from using Main entry method

I want to perform the same behavior that NUnit tests perform that it prevents using a Main method. In this case the error that I need is a good thing. Let me explain what I mean.

  1. I create a hello world application targeting the .net core

Project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>



</Project>

Code file: (default hello world c# code)

  1. If I then run that application it runs fine

  2. Add a reference to NUnit and my project file now contains.

.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NUnit" Version="3.12.0" />
    <PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
  </ItemGroup>

</Project>

  1. When I try to compile the project I get the error:

Error CS0017 Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.

That means that there is another Main method. That method is probably located on the NUnit nuget package I am referencing. This is the error I am trying to replicate!.


Now this is how I try to replicate the same error:

  1. I remove the NUnit nugget package having no references to NUnit on my hello world application.

  2. Create a Project ClassLibrary1 with the following code:

    public class MyLib { static void Main() { Console.WriteLine("fooooo"); // do something } }

  3. Have my hello world application reference that project:

enter image description here

When I compile I get no errors even though there are 2 Main methods!

How does NUnit manages to prevent using a Main method? How can I replicate the same behavior? I want to create an assembly that when referenced it prevents executing the Main method.





Aucun commentaire:

Enregistrer un commentaire