I am using ASP.NET.Core to embed a web server into a large legacy desktop application. My middleware components need to reference pre-existing application objects.
With difficulty I have got this working using the native DI container, but the resulting code is extraordinarily obtuse and opaque.
What I would really like to do, is to explicitely inject the dependencies, which are specific pre-existing object instances, through constructor parameters. The auto-magic of the DI container isn't giving me any benefits, just a lot of pain!
Is it possible to use ASP.NET.Core without the DI Container?
Here's some simplified code to illustrate my current solution:
class Dependency
{
public string Text { get; }
public Dependency(string text) => Text = text;
}
class MyMiddleware
{
private readonly RequestDelegate _next;
private readonly Dependency _dep1;
private readonly Dependency _dep2;
public MyMiddleware(RequestDelegate next, Dependency dep1, Dependency dep2)
{
_next = next;
_dep1 = dep1;
_dep2 = dep2;
}
public Task InvokeAsync(HttpContext context)
{
return context.Response.WriteAsync(_dep1.Text + _dep2.Text);
}
}
Startup and application code:
class Startup
{
private readonly Dependency _dep1;
private readonly Dependency _dep2;
public Startup(Dependency dep1, Dependency dep2)
{
_dep1 = dep1;
_dep2 = dep2;
}
public void Configure(IApplicationBuilder appBuilder)
{
appBuilder.UseMiddleware<MyMiddleware>(_dep1, _dep2);
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var dep1 = new Dependency("Hello ");
var dep2 = new Dependency("World");
int port = 5000;
StartWebServer(port, dep1, dep2);
Process.Start($"http://localhost:{port}");
}
void StartWebServer(int port, Dependency dep1, Dependency dep2)
{
IWebHostBuilder builder = new WebHostBuilder();
builder.UseUrls($"http://0.0.0.0:{port}/");
builder.UseKestrel();
builder.ConfigureServices(servicesCollection => servicesCollection.AddSingleton(new Startup(dep1, dep2)));
builder.UseStartup<Startup>();
IWebHost webHost = builder.Build();
var task = webHost.StartAsync();
}
}
Can this sample code be refactored to eliminate the DI container?