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