Scott Hanselman

Exploring ServiceStack's simple and fast web services on .NET Core

October 23, '16 Comments [22] Posted in Open Source | Web Services
Sponsored By

Northwind - ServiceStack styleI've been doing .NET Open Source since the beginning. Trying to get patches into log4net was hard without things like GitHub and Twitter. We emailed .patch files around and hoped for the best. It was a good time.

There's been a lot of feelings around .NET Open Source over the last decade or so - some positive, some negative. There's been some shining lights though and I'm going to do a few blog posts to call them out. I think having .NET Core be cross platform and open source will be a boon for the .NET Community. However, the community needs to also help out by using non-Microsoft OSS, supporting it, doing PRs, helping with docs, giving talks on new tech and spreading the word.

While some OSS projects are purely volunteer projects, ServiceStack has found some balance with a per-developer pricing model. They also support free usage for small projects. They've got deep integration with all major IDEs and support everything from VS, Xcode, IntelliJ IDEA, and the commandline.

ServiceStack Logo

One major announcement in the least few days as been ServiceStack 4.5.2 on .NET Core! Effectively one year to the day from the feature request and they did it! Their announcement paragraph says it best, emphasis mine.

Whilst the development and tooling experience is still in a transitionary period we believe .NET Core puts .NET Web and Server App development on the cusp of an exciting future - the kind .NET hasn’t seen before. The existing Windows hosting and VS.NET restraints have been freed, now anyone can develop using .NET’s productive expertly-designed and statically-typed mainstream C#/F# languages in their preferred editor and host it on the most popular server Operating Systems, in either an all-Linux, all-Windows or mixed ecosystem. Not only does this flexibility increase the value of existing .NET investments but it also makes .NET appeal to the wider and highly productive developer ecosystem who’ve previously disregarded .NET as an option.

Many folks ran (and run) ServiceStack on Mono, but it's time to move forward. While Mono is still a fantastic stack on many platforms that .NET Core doesn't support, for mainstream Linux, .NET Core is likely the better choice.

If you’re currently running ServiceStack on Mono, we strongly recommend upgrading to .NET Core to take advantage of its superior performance, stability and its top-to-bottom supported Technology Stack.

I also want to call out ServiceStack's amazing Release Notes. Frankly, we could all learn from Release Note this good - Microsoft absolutely included. These release notes are the now Gold Standard as far as I'm concerned. Additionally, ServiceStack's Live Demos are unmatched.

Enough gushing. What IS ServiceStack? It's a different .NET way for creating web services. I say you should give it a hard look if you're making Web Services today. They say this:

Service Stack provides an alternate, cleaner POCO-driven way of creating web services.

  • Simplicity
  • Speed
  • Best Practices
  • Model-driven, code-first, friction-free development
  • No XML config, no code-gen, conventional defaults
  • Smart - Infers intelligence from strongly typed DTOs
  • .NET and Mono
  • Highly testable - services are completely decoupled from HTTP
  • Mature - over 5+ years of development
  • Commercially supported and Continually Improved
  • and most importantly - with AutoQuery you get instant queryable APIs. Take a look at what AutoQuery does for a basic Northwind sample.

They've plugged into .NET Core and ASP.NET Core exactly as it was design. They've got sophisticated middleware and fits in cleanly and feels natural. Even more, if you have existing ServiceStack code running on .NET 4.x, they've designed their "AppHost" such that moving over the .NET Core is extremely simple.

ServiceStack has the standard "Todo" application running in both .NET Full Framework and .NET Core. Here's two sites, both .NET and both ServiceStack, but look what's underneath them:

Getting Started with Service Stack

There's a million great demos as I mentioned above with source at, but I love that ServiceStack has a Northwind Database demo here It even includes a Dockerfile. Let's check it out. I was able to get it running in Docker in seconds.

>git clone
>cd Northwind
>docker build -t "northwindss/latest" .
>docker run northwindss/latest
Project Northwind.ServiceModel (.NETStandard,Version=v1.6) was previously compiled. Skipping compilation.
Project Northwind.ServiceInterface (.NETStandard,Version=v1.6) was previously compiled. Skipping compilation.
Project Northwind (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
Hosting environment: Production
Content root path: /app/Northwind
Now listening on: https://*:5000
Application started. Press Ctrl+C to shut down.

Let's briefly look at the code, though. It is a great sample and showcases a couple cool features and also is nicely RESTful.

There's some cool techniques in here. It uses SqLITE for the database and the database itself is created with this Unit Test. Here's the ServiceStack AppHost (AppHost is their concept)

public class AppHost : AppHostBase
public AppHost() : base("Northwind Web Services", typeof(CustomersService).GetAssembly()) { }

public override void Configure(Container container)
new OrmLiteConnectionFactory(MapProjectPath("~/App_Data/Northwind.sqlite"), SqliteDialect.Provider));

//Use Redis Cache
//container.Register<ICacheClient>(new PooledRedisClientManager());


Plugins.Add(new AutoQueryFeature { MaxLimit = 100 });
Plugins.Add(new AdminFeature());

Plugins.Add(new CorsFeature());

Note host the AppHost base references the Assembly that contains the CustomersService type. That's the assembly that is the ServiceInterface. There's a number of Services in there - CustomersService just happens to be a simple one:

public class CustomersService : Service
public object Get(Customers request) =>
new CustomersResponse { Customers = Db.Select<Customer>() };

The response for /customers is just the response and a list of Customers:

public class Customers : IReturn<CustomersResponse> {}

public class CustomersResponse : IHasResponseStatus
public CustomersResponse()
this.ResponseStatus = new ResponseStatus();
this.Customers = new List<Customer>();

public List<Customer> Customers { get; set; }

public ResponseStatus ResponseStatus { get; set; }

Customers has a lovely clean GET that you can see live here: Compare its timestamp to the cached one at

[CacheResponse(Duration = 60 * 60, MaxAge = 30 * 60)]
public class CachedServices : Service
public object Get(CachedCustomers request) =>
Gateway.Send(new Customers());

public object Get(CachedCustomerDetails request) =>
Gateway.Send(new CustomerDetails { Id = request.Id });

public object Get(CachedOrders request) =>
Gateway.Send(new Orders { CustomerId = request.CustomerId, Page = request.Page });

You may find yourself looking at the source for the Northwind sample and wondering "where's the rest?" (no pun intended!) Turns out ServiceStack will do a LOT for you if you just let it!

The Northwind project is also an example of how much can be achieved with a minimal amount of effort and code. This entire website literally just consists of these three classes . Everything else seen here is automatically provided by ServiceStack using a code-first, convention-based approach. ServiceStack can infer a richer intelligence about your services to better able to provide more generic and re-usable functionality for free!

ServiceStack is an alternative to ASP.NET's Web API. It's a different perspective and a different architecture than what Microsoft provides out of the box. It's important and useful to explore other points of view when designing your systems. It's especially nice when the systems are so thoughtfully factored, well-documented and designed as ServiceStack. In fact, years ago I wrote their tagline: "Thoughtfully architected, obscenely fast, thoroughly enjoyable web services for all."

Have you used ServiceStack? Have you used other open source .NET Web Service/API frameworks? Share your experience in the comments!

Sponsor: Big thanks to Telerik! 60+ ASP.NET Core controls for every need. The most complete UI toolset for x-platform responsive web and cloud development. Try now 30 days for free!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Exploring Application Insights for disconnected or connected deep telemetry in ASP.NET Apps

October 19, '16 Comments [18] Posted in Azure
Sponsored By

Today on the ASP.NET Community Standup we learned about how you can use Application Insights in a disconnected scenario to get some cool - ahem - insights into your application.

Typically when someone sees Application Insights in the File | New Project dialog they assume it's a feature that only works in Azure, that will create some account for you and send your data to the cloud. While App Insights totally does do a lot of cool stuff when you have a cloud-hosted app and it does add a lot of value, it also supports a very useful "SDK only" mode that's totally offline.

Click "Add Application Insights to project" and then under "Send telemetry to" you click "Install SDK only" and no data gets sent to the cloud.

Application Insights dropdown - Install SDK only

Once you make your new project, can you learn more about AppInsights here.

For ASP.NET Core apps, Application Insights will include this package in your project.json - "Microsoft.ApplicationInsights.AspNetCore": "1.0.0" and it'll add itself into your middleware pipeline and register services in your Startup.cs. Remember, nothing is hidden in ASP.NET Core, so you can modify all this to your heart's content.

if (env.IsDevelopment())
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);

Request telemetry and Exception telemetry are added separately, as you like.

Make sure you show the Application Insights Toolbar by right-clicking your toolbars and ensuring it's checked.

Application Insights Dropdown Menu

The button it adds is actually pretty useful.

Application Insights Dropdown Menu

Run your app and click the Application Insights button.

NOTE: I'm using Visual Studio Community. That's the free version of VS you can get at I use it exclusively and I think it's pretty cool that this feature works just great on VS Community.

You'll see the Search window open up in VS. You can keep it running while you debug and it'll fill with Requests, Traces, Exceptions, etc.


I added a Exceptional case to /about, and here's what I see:

Searching for the last hours traces

I can dig into each issue, filter, search, and explore deeper:

Unhandled Exception

And once I've found something interesting, I can explore around it with the full details of the HTTP Request. I find the "telemetry 5 minutes before and after" query to be very powerful.

Track Operations

Notice where it says "dependencies for this operation?" That's not dependencies like "Dependency Injection" - that's larger system-wide dependencies like "my app depends on this web service."

You can custom instrument your application with the TrackDependancy API if you like, and that will cause your system's dependency to  light up in AppInsights charts and reports. Here's a dumb example as I pretend that putting data in ViewData is a dependency. It should be calling a WebAPI or a Database or something.

var telemetry = new TelemetryClient();

var success = false;
var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();
ViewData["Message"] = "Your application description page.";
telemetry.TrackDependency("ViewDataAsDependancy", "CallSomeStuff", startTime, timer.Elapsed, success);

Once I'm Tracking external Dependencies I can search for outliers, long durations, categorize them, and they'll affect the generated charts and graphs if/when you do connect your App Insights to the cloud. Here's what I see, after making this one code change. I could build this kind of stuff into all my external calls AND instrument the JavaScript as well. (note Client and Server in this chart.)

Application Insight Maps

And once it's all there, I can query all the insights like this:

Querying Data Live

To be clear, though, you don't have to host your app in the cloud. You can just send the telemetry to the cloud for analysis. Your existing on-premises IIS servers can run a "Status Monitor" app for instrumentation.

Application Insights Charts

There's a TON of good data here and it's REALLY easy to get started either:

  • Totally offline (no cloud) and just query within Visual Studio
  • Somewhat online - Host your app locally and send telemetry to the cloud
  • Totally online - Host your app and telemetry in the cloud

All in all, I am pretty impressed. There's SDKs for Java, Node, Docker, and ASP.NET - There's a LOT here. I'm going to dig deeper.

Sponsor: Big thanks to Telerik! 60+ ASP.NET Core controls for every need. The most complete UI toolset for x-platform responsive web and cloud development. Try now 30 days for free!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Learning Arduino the fun way - Writing Games with Arduboy

October 18, '16 Comments [3] Posted in Hardware | Open Source
Sponsored By

IMG_1666My kids and I are always tinkering with gadgets and electronics. If you follow me on Instagram you'll notice our adventures as we've built a small Raspberry Pi powered arcade, explored retro-tech, built tiny robots, 3D printed a GameBoy (PiGrrl, in fact), and lots more.

While we've done a bunch of small projects with Arduinos, it's fair to say that there's a bit of a gap when one is getting started with Arduino. Arduinos aren't like Raspberry PIs. They don't typically have a screen or boot to a desktop. They are amazing, to be sure, but not everyone lights up when faced with a breadboard and a bunch of wires.

The Arduboy is a tiny, inexpensive hardware development platform based on Arduino. It's like a GameBoy that has an Arduino at its heart. It comes exactly as you see in the picture to the right. It uses a micro-USB cable (included) and has buttons, a very bright black and white OLED screen, and a speaker. Be aware, it's SMALL. Smaller than a GameBoy. This is a game that will fit in an 8 year old's pocket. It's definitely-fun sized and kid-sized. I could fit a half-dozen in my pocket.

The quick start for the Arduboy is quite clear. My 8 year old and I were able to get Hello World running in about 10 minutes. Just follow the guide and be sure to paste in the custom Board Manager URL to enable support in the IDE for "Arduboy."

The Arduboy is just like any other Arduino in that it shows up as a COM port on your Windows machine. You use the same free Arduino IDE to program it, and you utilize the very convenient Arduboy libraries to access sound, draw on the screen, and interact with the buttons.

To be clear, I have no relationship with the Arduboy folks, I just think it's a killer product. You can order an Arduboy for US$49 directly from their website. It's available in 5 colors and has these specs:


  • Processor: ATmega32u4 (same as Arduino Leonardo & Micro)
  • Memory: 32KB Flash, 2.5KB RAM, 1KB EEPROM
  • Connectivity: USB 2.0 w/ built in HID profile
  • Inputs: 6 momentary tactile buttons
  • Outputs: 128x64 1Bit OLED, 2 Ch. Piezo Speaker & Blinky LED
  • Battery: 180 mAh Thin-Film Lithium Polymer
  • Programming: Arduino IDE, GCC & AVRDude

There's also a friendly little app called Arduboy Manager that connects to an online repository of nearly 50 games and quickly installs them. This proved easier for my 8 year old than downloading the source, compiling, and uploading each time he wanted to try a new game.

The best part about Arduboy is its growing community. There's dozens if not hundreds of people learning how to program and creating games. Even if you don't want to program one, the list of fun games is growing every day.

The games are all open source and you can read the code while you play them. As an example, there's a little game called CrazyKart and the author says it's their first game! The code is on GitHub. Just clone it (or download a zip file) and open the .ino file into your Arduino IDE.

Arduboys are easy to program

Compile and upload the app while the Arduboy is connected to your computer. The Arduboy holds just one game at a time. Here's Krazy Kart as a gif:

Because the Arduboy is so constrained, it's a nice foray into game development for little ones - or any one. The screen is just 128x64 and most games use sprites consisting of 1 bit (just black or white). The Arduboy library is, of course, also open source and includes the primitives that most games will need, as well as lots of examples. You can draw bitmaps, swap frames, draw shapes, and draw characters.

We've found the Arduboy to be an ideal on ramp for the kids to make little games and learn basic programming. It's a bonus that they can easily take their games with them and share with their friends.

Related Links

Sponsor: Thanks to Redgate this week! Discover the world’s most trusted SQL Server comparison tool. Enjoy a free trial of SQL Compare, the industry standard for comparing and deploying SQL Server schemas.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Exploring ASP.NET Core with Docker in both Linux and Windows Containers

October 14, '16 Comments [23] Posted in ASP.NET | Docker | Open Source
Sponsored By

In May of last year doing things with ASP.NET and Docker was in its infancy. But cool stuff was afoot. I wrote a blog post showing how to publish an ASP.NET 5 (5 at the time, now Core 1.0) app to Docker. Later in December of 2015 new tools like Docker Toolbox and Kitematic made things even easier. In May of 2016 Docker for Windows Beta continued to move the ball forward nicely.

I wanted to see how things are looking with ASP.NET Core, Docker, and Windows here in October of 2016.

I installed these things:

Docker for Windows is really nice as it automates setting up Hyper-V for you and creates the Docker host OS and gets it all running. This is a big time saver.

Hyper-V manager

There's my Linux host that I don't really have to think about. I'll do everything from the command line or from Visual Studio.

I'll say File | New Project and make a new ASP.NET Core application running on .NET Core.

Then I right click and Add | Docker Support. This menu comes from the Visual Studio Tools for Docker extension. This adds a basic Dockerfile and some docker-compose files. Out of the box, I'm all setup to deploy my ASP.NET Core app to a Docker Linux container.

ASP.NET Core in a Docker Linux Container

Starting from my ASP.NET Core app, I'll make sure my base image (that's the FROM in the Dockerfile) is the base ASP.NET Core image for Linux.

FROM microsoft/aspnetcore:1.0.1
ENTRYPOINT ["dotnet", "WebApplication4.dll"]
ARG source=.
COPY $source .

Next, since I don't want Docker to do the building of my application yet, I'll publish it locally. Be sure to read Steve Lasker's blog post "Building Optimized Docker Images with ASP.NET Core" to learn how to have one docker container build your app and the other run it it. This optimizes server density and resource.

I'll publish, then build the images, and run it.

>dotnet publish

>docker build bin\Debug\netcoreapp1.0\publish -t aspnetcoreonlinux

>docker images
aspnetcoreonlinux latest dab2bff7e4a6 28 seconds ago 276.2 MB
microsoft/aspnetcore 1.0.1 2e781d03cb22 44 hours ago 266.7 MB

>docker run -it -d -p 85:80 aspnetcoreonlinux

>docker ps
1cfcc8e8e7d4 aspnetcoreonlinux "dotnet WebApplicatio" 2 seconds ago Up 1 seconds>80/tcp clever_archimedes

And there's my ASP.NET Core app running in Docker. So I'm running Windows, running Hyper-V, running a Linux host that is hosting Docker containers.

What else can I do?

ASP.NET Core in a Docker Windows Container running Windows Nano Server

There's Windows Server, there's Windows Server Core that removes the UI among other things and there's Windows Nano Server which gets Windows down to like hundreds of megs instead of many gigs. This means there's a lot of great choices depending on what you need for functionality and server density. Ship as little as possible.

Let me see if I can get ASP.NET Core running on Kestrel under Windows Nano Server. Certainly, since Nano is very capable, I could run IIS within the container and there's docs on that.

Michael Friis from Docker has a great blog post on building and running your first Docker Windows Server Container. With the new Docker for Windows you can just right click on it and switch between Linux and Windows Containers.

Docker switches between Mac and Windows easily

So now I'm using Docker with Windows Containers. You may not know that you likely already have Windows Containers! It was shipped inside Windows 10 Anniversary Edition. You can check for Containers in Features:

Add Containers in Windows 10

I'll change my Dockerfile to use the Windows Nano Server image. I can also control the ports that ASP.NET talks on if I like with an Environment Variable and Expose that within Docker.

FROM microsoft/dotnet:nanoserver
ENTRYPOINT ["dotnet", "WebApplication4.dll"]
ARG source=.
COPY $source .

Then I'll publish and build...

>dotnet publish
>docker build bin\Debug\netcoreapp1.0\publish -t aspnetcoreonnano

Then I'll run it, mapping the ports from Windows outside to the Windows container inside!

NOTE: There's a bug as of this writing that affects how Windows 10 talks to Containers via "NAT" (Network Address Translation) such that you can't easily go http://localhost:82 like you (and I) want to. Today you have to hit the IP of the container directly. I'll report back once I hear more about this bug and how it gets fixed. It'll show up in Windows Update one day. The workaround is to get the IP address of the container from docker like this:  docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" HASH

This bug has been fixed in the Windows 10 April Update. Details here Localhost Access to Windows Container Ports

So I'll run my ASP.NET Core app on Windows Nano Server (again, to be clear, this is running on Windows 10 and Nano Server is inside a Container!)

>docker run -it -d -p 88:82 aspnetcoreonnano

>docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" afa

Now I can hit that site with Once that bug above is fixed, it'll get hit and routed like any container.

The best part about Windows Containers is that they are fast and lightweight. Once the image is downloaded and build on your machine, you're starting and stopping them in seconds with Docker.

BUT, you can also isolate Windows Containers using Docker like this:

docker run --isolation=hyperv -it -d -p 86:82 aspnetcoreonnano

So now this instance is running fully isolated within Hyper-V itself. You get the best of all worlds. Speed and convenient deployment plus optional and easy isolation.

ASP.NET Core in a Docker Windows Container running Windows Server Core 2016

I can then change the Dockerfile to use the full Windows Server Core image. This is 8 gigs so be ready as it'll take a bit to download and extract but it is really Windows. You can also choose to run this as a container or as an isolated Hyper-V container.

Here I just change the FROM to get a Windows Sever Core with .NET Core included.

FROM microsoft/dotnet:1.0.0-preview2-windowsservercore-sdk
ENTRYPOINT ["dotnet", "WebApplication4.dll"]
ARG source=.
COPY $source .

NOTE: I hear it's likely that the the .NET Core on Windows Server Core images will likely go away. It makes more sense for .NET Core to run on Windows Nano Server or other lightweight images. You'll use Server Core for heavier stuff, and Server is nice because it means you can run "full" .NET Framework apps in containers! If you REALLY want to have .NET Core on Server Core you can make your own Dockerfile and easily build and image that has the things you want.

Then I'll publish, build, and run again.

>docker images
aspnetcoreonnano latest 7e02d6800acf 24 minutes ago 1.113 GB
aspnetcoreonservercore latest a11d9a9ba0c2 28 minutes ago 7.751 GB

Since containers are so fast to start and stop I can have a complete web farm running with Redis in a Container, SQL in another, and my web stack in a third. Or mix and match.

>docker ps
d32a981ceabb aspnetcoreonwindows "dotnet WebApplicatio">82/tcp compassionate_blackwell
a179a48ca9f6 aspnetcoreonnano "dotnet WebApplicatio">82/tcp determined_stallman
170a8afa1b8b aspnetcoreonnano "dotnet WebApplicatio">82/tcp agitated_northcutt
afafdbead8b0 aspnetcoreonnano "dotnet WebApplicatio">82/tcp naughty_ramanujan
2cf45ea2f008 a7fa77b6f1d4 "dotnet WebApplicatio">82/tcp sleepy_hodgkin


Again, go check out Michael's article where he uses Docker Compose to bring up the ASP.NET Music Store sample with SQL Express in one Windows Container and ASP.NET Core in another as well as Steve Lasker's blog (in fact his whole blog is gold) on making optimized Docker images with ASP.NET Core.

IMAGE ID            RESPOSITORY                   TAG                 SIZE
0ec4274c5571 web optimized 276.2 MB
f9f196304c95 web single 583.8 MB
f450043e0a44 microsoft/aspnetcore 1.0.1 266.7 MB
706045865622 microsoft/aspnetcore-build 1.0.1 896.6 MB

Steve points out a number of techniques that will allow you to get the most out of Docker and ASP.NET Core.

The result of all this means (IMHO) that you can use ASP.NET Core:

  • ASP.NET Core on Linux
    • within Docker containers
    • in any Cloud
  • ASP.NET Core on Windows, Windows Server, Server Core, and Nano Server.
    • within Docker windows containers
    • within Docker isolated Hyper-V containers

This means you can choose the level of feature support and size to optimize for server density and convenience. Once all the tooling (the Docker folks with Docker for Windows and the VS folks with Visual Studio Docker Tools) is baked, we'll have nice debugging and workflows from dev to production.

What have you been doing with Docker, Containers, and ASP.NET Core? Sound off in the comments.

Sponsor: Thanks to Redgate this week! Discover the world’s most trusted SQL Server comparison tool. Enjoy a free trial of SQL Compare, the industry standard for comparing and deploying SQL Server schemas.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

How to reference an existing .NET Framework Project in an ASP.NET Core 1.0 Web App

October 8, '16 Comments [25] Posted in ASP.NET | ASP.NET MVC
Sponsored By

I had a reader send me a question yesterday. She basically wanted to use her existing .NET Framework libraries in an ASP.NET Core application, and it wasn't super clear how to do it.

I have a quick question for you regarding core. We are rewriting our website using core, empty from the bottom up. We have 2 libraries written in .net 4.6 . One is our database model and repositories and the other is a project of internal utilities we use a lot. Unfortunately we cannot see how to reference these two projects in our .net core project.

It can be a little confusing. As I mentioned earlier this week, some people don't realize that ASP.NET Core 1.0 (that's the web framework bit) runs on either .NET Core or .NET Framework 4.6 aka "Full Framework."

ASP.NET Core 1.0 runs on ASP.NET 4.6 nicely

When you make a new web project in Visual Studio you see (today) this dialog. Note in the dropdown at the top you can select your minimum .NET Framework version. You can select 4.6.2, if you like, but I'll do 4.5.2 to be a little more compatible. It's up to you.

File New Project

This dialog could use clearer text and hopefully it will soon.

  • There's the regular ASP.NET Web Application at the top. That's ASP.NET 4.6 with MVC and Web API. It runs on the .NET Framework.
  • There's ASP.NET Core 1.0 running on .NET Core. That's cross platform. If you select that one you'll be able to run your app anywhere but you can't reference "Full" .NET Framework assemblies as they are just for Windows.  If you want to run anywhere you need to use .NET Standard APIs that will run anywhere.
  • There's ASP.NET Core 1.0 running on .NET Framework. That's the new ASP.NET Core 1.0 with unified MVC and Web API but running on the .NET Framework you run today on Windows.

As we see in the diagram above, ASP.NET Core 1.0 is the new streamlined ASP.NET  that can run on top of both .NET Framework (Windows) and .NET Core (Mac/Windows/Linux).

I'll chose ASP.NET Core on .NET Framework and I'll see this in my Solution Explorer:

Web App targeting .NET Framework 4.5.2

I've got another DLL that I made with the regular File | New Project | Class Library.

New Class Library

Then I reference it the usual way with Add Reference and it looks like this in the References node in Solution Explorer. Note the icon differences.

Adding ClassLibrary1 to the References Node in Solution Explorer

If we look in the project.json (Be aware that this will change for the better in the future when project.json's functionality is merged with csproj and msbuild) you'll note that the ClassLIbrary1 isn't listed under the top level dependencies node, but as a framework specific dependency like this:

"dependencies": {
"Microsoft.StuffAndThings": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.1",

"frameworks": {
"net452": {
"dependencies": {
"ClassLibrary1": {
"target": "project"

Notice also that in this case it's a type="project" dependency in this case as I didn't build a NuGet package and reference that.

Since the .NET Core tooling is in preview there are some gotchas when doing this today.

  • Make sure that all your class libraries are targeting an appropriate version of the .NET Framework.
    • For example, don't have a 4.5.2 Web App targeting a 4.6.2 Class Library. This could bite you in subtle ways if things don't line up in production.
  • dotnet restore at the command line may well get confused and give you an error like:
    • Errors in D:\github\WebApplication2\src\WebApplication2\project.json - Unable to resolve 'ClassLibrary1' for '.NETFramework,Version=v4.5.2'.
    • Use Visual Studio to build or run msbuild at the command line.
  • You can restore packages from the command line with nuget.exe version 3.4.4 or greater if you restore on the .sln file like this:
    • D:\github\WebApplication2>nuget restore WebApplication2.sln
      MSBuild auto-detection: using msbuild version '14.0' from 'C:\Program Files (x86)\MSBuild\14.0\bin'.
    • I recommend you run nuget.exe to see what version you have and run nuget update -self to have it update itself.

These gotchas will be fixed when the tooling is finalized.

Hope this helps!

Sponsor: Big thanks to Telerik for sponsoring the blog this week! 60+ ASP.NET Core controls for every need. The most complete UI toolset for x-platform responsive web and cloud development. Try now 30 days for free!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.