I currently have a ASP.NET Core application implementing a basic web API. I have a need to write a script that hooks into the same environment with access to at least the database, but can't find a place to add new entry points to the application. I can easily look at string[] args in the Main method in Program.cs and not start the server, but I don't see how I can load up the environment and run arbitrary code without just standing up the normal Kestrel server. I'm pretty new to the .NET world so I'm hoping there is an easy way to do this that I've just failed to find in the documentation.
Basically I'd like to be able to run something like dotnet run foo which would execute some synchronous piece of code on the server instead of starting up the normal kestrel server.
You can do this by adding new projects. The idea is to have three projects co-exist in your solution:
Steps to go from a single-project ASP.NET Core application to the configuration above (assuming that you're using Visual Studio) look something like:
CommonStartup class to your Common project. Give it a public static void ConfigureServices(IServiceCollection services) and cut and paste across any service configuration from your ASP.NET Core application's Startup.ConfigureServices method that you want to share with your Scripts project. Add a call to CommonStartup.ConfigureServices(services) to Startup.ConfigureServices method in the ASP.NET Core project. (You'll need to add references to Microsoft.Extensions.DependencyInjection; and Microsoft.Extensions.DependencyInjection.Abstractions; to the Common project and a reference to Common to the ASP.NET Core project; Visual Studio should offer these as sidebar actions.At the start of your Scripts project's Main method, add:
var services = new ServiceCollection();
CommonStartup.ConfigureServices(services);
var provider = services.BuildServiceProvider();
(You'll once again have to add references.)
var widgetFactory = provider.GetService<IWidgetFactory>().You can build and run your script by running dotnet run from within the folder of your Scripts project.
If you want multiple executable scripts, just add a switch statement to your Main method that does something different depending upon the value of args[0], then call your scripts with dotnet run wibble, dotnet run wobble, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With