If you define two target frameworks in project.json
(like aspnetcore
and net451
), then two separate dlls will be created and put into lib/aspnetcore
and lib/net451
inside the nuget package. Nuget will know which one to use, based on the target framework of the project that consumes the package.
Now, you can use #ifdef
statements in your library to distinguish, which parts of code should be compiled only for specified platforms.
A simple example:
using System;
namespace MyLib
{
#if NETFX
using HttpContext = System.Web.HttpContext;
#elif NETCORE
using HttpContext = Microsoft.AspNetCore.Http.HttpContext;
#endif
public class MyClass
{
public string GetUserAgent(HttpContext ctx)
{
return ctx.Request.Headers["User-Agent"];
}
public void WriteToResponse(HttpContext ctx, string text)
{
#if NETFX
ctx.Response.Output.Write(text);
#elif NETCORE
var bytes = System.Text.Encoding.UTF8.GetBytes(text);
ctx.Response.Body.Write(bytes, 0, bytes.Length);
#endif
}
}
}
To make these switches work, you have to define framework-specific constants in project.json:
"frameworks": {
"netcoreapp1.0": {
"buildOptions": {
"define": [
"NETCORE"
]
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
},
"Microsoft.AspNetCore.Http": "1.0.0"
}
},
"net451": {
"buildOptions": {
"define": [
"NETFX"
]
},
"dependencies": {
"Microsoft.AspNet.WebApi": "5.2.3"
},
"frameworkAssemblies": {
"System.Web": "4.0.0.0"
}
}
},
Note that both frameworks have different set of dependencies. HttpContext
here will be a different type when compiled for netcoreapp and for net451. Fortunatelly, these types have very similar methods, so often times you can use them in the same way, without #ifdef
s (like in GetUserAgent
). Other times, you won't be able to avoid it (like in WriteToResponse
).
Now, in a AspNet Core project you could use this library like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (ctx, next) => {
var lib = new MyLib.MyClass();
var msg = lib.GetUserAgent(ctx);
lib.WriteToResponse(ctx, "user agent is: " + msg);
});
}
And in old AspNet MVC:
public class HomeController : Controller
{
public ActionResult Index()
{
var lib = new MyLib.MyClass();
var msg = lib.GetUserAgent(System.Web.HttpContext.Current);
lib.WriteToResponse(System.Web.HttpContext.Current, "user agent is: " + msg);
return new HttpStatusCodeResult(200);
}
}
Full source code on github.