Skip to main content
Home  ›  Blog

Shared .cs Code in Razor and WebApi (new in 10.01)

Sharing code in parts of your app is now super easy, with the new feature compile .cs files on the fly. This means your code can now be written for use in both Razor and WebApi. 

Basics: CreateInstance(...) 

Previously CreateInstance could only be used in razor, and it was only able to compile .cshtml files. We've now invested heavily into this and made it so it can also compile .cs files and is also available in WebApi controllers. 

So you can now write simple classes in .cs files, and get them using:

  • var bl = CreateInstance("BusinessLogic.cs");

This looks for a class BusinessLogic in the file. If you have many classes in the file and want to get a different one, use this syntax:

  • var accounting = CreateInstance("BusinessLogic.cs", name: "Accounting");

The resulting object is dynamic, so anything you write like ".Calculate()" etc. will be processed at runtime. 

The Great: Share Code in Razor and WebApi

We invested heavily to ensure that it works both in Razor and WebApi. So the command CreateInstance now also exists in the WebApi, and will work identically. This will make coding much easier!

The Awesome: You can also have Context

A core challenge in many applications is that the shared code also needs to know things about DNN or the current app. If CreateInstance only got the class for you, then your code would not know about this, and you would end up passing a lot of parameters around in each function call. But we decided we can do better: If your code is a basic class, that's all you get. But if your code inherits from ToSic.Sxc.Code.WithContext or ToSic.Sxc.Code.WithDnnContext, all the context information like the Dnn object, the App object, Data AND all the common methods like AsDynamic(...), CreateDataSource<T>() etc. are immediately available in your class. How awesome is that? 😎

Version Requirements and Demo

All this works from 2sxc 10.01 and newer (just released). We also extended our Razor Tutorial to cover this topic, with examples and everything.

Love From Switzerland, 
iJungleboy


Daniel Mettler grew up in the jungles of Indonesia and is founder and CEO of 2sic internet solutions in Switzerland and Liechtenstein, an 20-head web specialist with over 800 DNN projects since 1999. He is also chief architect of 2sxc (see github), an open source module for creating attractive content and DNN Apps.

Read more posts by Daniel Mettler