我正在使用ASP.NET.Core将Web服务器嵌入到一个庞大的遗留桌面应用程序中。我的中间件组件需要引用预先存在的应用程序对象。
通过使用本地DI容器,我费了很大力气才让它工作,但最终的代码非常晦涩难懂。
我真正想做的是显式地通过构造函数参数注入依赖项(即特定的预先存在的对象实例)。 DI容器的自动魔法没有给我任何好处,只有很多痛苦!
是否可能在不使用DI容器的情况下使用ASP.NET.Core?
以下是一些简化的代码以说明我的当前解决方案:
通过使用本地DI容器,我费了很大力气才让它工作,但最终的代码非常晦涩难懂。
我真正想做的是显式地通过构造函数参数注入依赖项(即特定的预先存在的对象实例)。 DI容器的自动魔法没有给我任何好处,只有很多痛苦!
是否可能在不使用DI容器的情况下使用ASP.NET.Core?
以下是一些简化的代码以说明我的当前解决方案:
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);
}
}
启动和应用程序代码:
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();
}
}
这个示例代码能否进行重构以消除DI容器的使用?
new
关键字创建实例即可。 - OlegI