ASP.NET 5: Using shared sources

ASP.NET 5 supports code sharing between projects. It’s not about referencing libraries or something related to portable libraries – it’s different. Libraries can share their source that is compiled to referencing project output. In this posting I will show you how this new source sharing system works.

Sample solution

ASP.NET 5: Library with shared sources folderSuppose we have library project and we want to share source of some classes to application that refer to this library.

Image on right illustrates the situation. AspNetMvc6.Common is the library where we want to share all C# files that are in Shared folder. The name of folder can be actually whatever you like. You don’t even need folder for shared sources if you prefer to keep shared sources in project root.

AspNetMvc6.WebApplication is application that refers to AspNetMvc6.Common through dependencies defined in project.json.

Sharing files to other projects

Now let’s share all C# files in our library to other applications. To do this we add new setting to project.json file of library project.

ASP.NET 5: Sharing code to other projects

Where is shared class?

Now let’s build our application and see if MySharedClass is compiled to web application or not. To do this I open application file in JetBrains dotPeek (yes, it’s free tool) to see what’s inside it.

ASP.NET 5: Shared class in web application dll

We can see that our web application assembly contains MySharedClass from library project and we didn’t used file links or any other Visual Studio level trciks to achieve it.

Wrapping up

Sharing code between libraries and applications is easy in ASP.NET 5. By example, we can make two assemblies use their helper classes this way and shared sources will be available also through NuGet packages. Good example by Microsoft comes from ASP.NET MVC commons library.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    One thought on “ASP.NET 5: Using shared sources

    • November 21, 2014 at 9:18 am
      Permalink

      Hi,

      I’m wondering what will happen if two assemblies reference the same share folder and we want to use them in a third one? The MySharedClass would be defined in both assemblies?

      Is there a requirement to make them internal?

    Leave a Reply

    Your email address will not be published. Required fields are marked *