You can do this by adding new projects. The idea is to have three projects co-exist in your solution:
- the ASP.NET Core application, and
- a .NET Core Console App containing your executable scripts, and
- a .NET Class Library containing common dependencies of the two and containing service collection configuration, so that you can use the ASP.NET DI container from within your scripts
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:
- Right-click your solution in Solution Explorer, go to Add -> New Project..., and select the project type Console App (.NET Core). Give it a name (e.g. Scripts) and click OK.
- Add another project with type Class Library (.NET Core), named e.g. Common.
- Migrate any classes that you want to use from the ASP.NET Core project to the Common project.
- Add a
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.)
- You can now use the DI system from within your Scripts project to get instances of classes, by writing e.g.
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.