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.
Suppose 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.
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.
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.
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.