Reference a class library from UWP and ASP.NET 5

坚强是说给别人听的谎言 提交于 2020-01-02 01:20:07

问题


I am trying to create a class library that'll contain common objects (mainly DTOs) of a WebAPI (using ASP.NET 5) and a consuming UWP App. However, I have not yet figured out how to create the class library such that it can be referenced from both other projects.

What I have tried so far:
First, I tried a Class Library (Package), which can be found under Web. This type of library can be referenced from the ASP.NET project without problems, but when trying to reference it from the UWP project, I get the following message:

A reference to 'ClassLibrary1' could not be added. 

Next, I tried a Class Library (Windows Universal), which can be found under Windows > Universal. This can easily be references from the UWP project, but when trying to reference it from ASP.NET, I get:

The following projects are not supported as references : 

  - The project ClassLibrary2 has a target framework that is incompatible or has version higher than the current project and cannot be referenced.

So: How can I create a class library that can be used in both an ASP.NET 5 project and an UWP project?


回答1:


The .Net Standard class library should be thought of as a successor to the portable class library. Both aim to facilitate sharing code (in this case model objects/DTOs) between different .Net platforms.

In Visual Studio 2017, you can now choose a .Net Standard class library template. This class library can bet set to target different versions of the .Net Standard. The version of the .Net Standard that you should target will depend upon what .Net platforms you wish share code between.

For this particular question, we wish to support a Universal Windows Platform (UWP) app and Asp.Net Core app. So, we should refer to this compatibility table to determine the version of the .Net Standard that will support both of these platforms. In this case, it would be .Net Standard 1.4. Once you have set the class library to target the .Net Standard 1.4, you can add references to the class library from your UWP and Asp.Net core projects.

In order to better understand what the .Net Standard is and how it facilitates code sharing, I suggest reviewing the following:

  1. Introducing .NET Standard
  2. Video Series on .NET Standard (this is particularly good)
  3. .Net Standard FAQ



回答2:


What you need is a Portable Class Library (under Windows).

Since you're only targetting ASP.NET 5 and Windows 10, you can limit the platforms to these two only, but there's no "error" in supporting more platforms (it can limit how much of the shared API is available though).



来源:https://stackoverflow.com/questions/34028887/reference-a-class-library-from-uwp-and-asp-net-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!