by maushu · 2y ago · 0 comments
Asp.net is very overbearing (even using minimal APIs) when you want to use other Microsoft utilities like DI, logging or config since it wants to be the main entry of the application.
Never found an easy way to use the host feature with a optional web application where they both shared the DI. Note that this is more a problem with the generic host than asp.net itself.
We're using ASP.NET Core Minimal APIS for both API and UI (if configured to run in that mode )
var builder = WebApplication.CreateBuilder([]);
builder.WebHost.UseUrls($"http://127.0.0.1:0");
builder.Services.AddSingleton(...);
var app = builder.Build();
app.Map...
await app.StartAsync(cancellationToken);
We run multiple of these at a time and have no problems. public static ConfigurationExtensions{
public static AddMyApp(this IServiceCollection services){
services.AddScoped<IFooService,FooService>();
}
}
//In console app:
var consoleBuilder = Host.CreateApplicationBuilder(args);
consoleBuilder.Services.AddMyApp();
...
//pseudocode - in real world you'd put this in another class or method called by the commandline code:
if(webHostCommandLineSwitch){
var webBuilder = WebApplication.CreateBuilder(args);
webBuilder.Services.AddMyApp();
...
}