.net core classlibrary calling .net framework clas

2020-03-24 07:08发布

问题:

Could not find an answer to my doubts and hopefully somebody can clarify.

I Have created a dummy solution with

  • 1 class library(.net framework)
  • 1 .net core library

Tried to reference either way but I cant,they are not compatible,fine makes sense.

Now my question

I have a utility class library(.net framework)with extensions,helpers etc... that is used by winforms-wpf-asp.net mvc 4,5 apps now with the event of .net core it looks to me that I cannot use this library anymore unless I port it to .net core,which then i cannot use with my other apps.

What is the correct approach?

Am i missing the obvious?

回答1:

Sharing code between a normal .NET library and a Core project did not work for me via simply using a Shared project, because I could not reference it from the Core project.

However, with a little trick I could make it work.

Let me explain with this folder/file structure:

[ProjectName] // Root of Core project
    project.json
    [ProjectName].xproj

    Shared // Root of Shared project
        [ProjectName].Shared.projitems
        [ProjectName].Shared.shproj 
        // -- Source files here --

    Net // Root of .NET project
        [ProjectName].csproj
        Properties
            AssemblyInfo.cs // For both Core and .NET project
        // NO source files here

So, you will need 3 projects, of course: a Core project, a normal .NET project, and a Shared project.
The Shared project has all the source files.
The .NET project references the Shared project, so it also has those files.
The Core project sees all the files the Shared project has, so it also has the same files.

That's it. You now can have common source code files for the .NET and the Core project.

A few notes:

  • Do NOT ever put the .shroj and the .csproj into the same folder. For me, it totally turned off intellisense in VS (2015). This information costed a lot of pain for me...
  • You can use #if -s to fine tune the common code
  • You can also use NuGet 2 in the .NET project with the above folder structure.
    • Note, that if you'd put the (NuGet 2) packages.config into the same folder where the (NuGet 3) project.json is located, the latter would totally overwrite the earlier.


回答2:

You could try to use a shared library project. It compiles against the platform of the referencing application/library, so to speak. That gives you the ability to create class libraries targeting different platforms without the need to duplicate any code, but it may require some #if...

https://blogs.msdn.microsoft.com/dotnet/2014/04/21/sharing-code-across-platforms/