【发布时间】:2022-12-19 22:36:09
【问题描述】:
我正在尝试使用 CoreWCF 包将旧的 WCF 服务转换为 ASP.NET Core Web API。这个现有服务的一个关键特性是它由其他应用程序自行托管,并且能够优雅地启动和停止,而不会造成内存泄漏。
我已经能够弄清楚如何启动和停止原型服务。然而,在执行了一些压力测试之后,似乎我在某处留下了内存泄漏,遗憾的是我此时没有想法或可用的文档。我也在考虑 ASP.NET Core Web API 不应该像这样使用,我误解了这一点,如果是这样,请务必让我知道。我也为代码的卡车道歉,但我不确定什么与问题相关或不相关。
我的原型服务的代码如下所示:
配置虚拟主机:
private void CreateWebHostBuilder(){
host = WebHost.CreateDefaultBuilder()
.UseKestrel(options =>
{
options.AllowSynchronousIO = true;
options.ListenLocalhost(Startup.PORT_NR);
options.ConfigureHttpsDefaults(
options => options.ClientCertificateMode = ClientCertificateMode.RequireCertificate
);
})
.ConfigureLogging(logging => { logging.SetMinimumLevel(LogLevel.Warning); })
.UseSetting(WebHostDefaults.DetailedErrorsKey, "true")
.UseShutdownTimeout(TimeSpan.FromSeconds(1))
.UseStartup<Startup>()
.Build();
}
在Startup 类中:
配置IApplicationBuilder:
public void Configure(IApplicationBuilder app){
app.UseServiceModel(builder =>
{
// Add the Echo Service
builder.AddService<EchoService>()
// Add service web endpoint
.AddServiceWebEndpoint<EchoService, IEchoService>(
WEB_API_PATH,behavior => { behavior.HelpEnabled = true;}
);
});
app.UseMiddleware<SwaggerMiddleware>();
app.UseSwaggerUI();
app.UseAuthentication();
}
配置服务:
public void ConfigureServices(IServiceCollection services){
services.AddServiceModelWebServices()
.AddHostedService<EchoService>()
.AddSingleton(new SwaggerOptions())
.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate();
}
服务接口:
[ServiceContract]
[OpenApiBasePath($"/{Startup.WEB_API_PATH}")]
public interface IEchoService : IHostedService {
[OperationContract]
[WebGet(UriTemplate = "/hello")]
[OpenApiOperation(Description = "Method used to receive a friendly \"Hello world\"",
Summary = "Hello world")]
[OpenApiResponse(Description = "OK Response", StatusCode = HttpStatusCode.OK)]
string HelloWorld();
}
实施的服务:
public class EchoService : IEchoService {
public EchoService() { }
public string HelloWorld() {
return "Hello world!";
}
public Task StartAsync(CancellationToken cancellationToken) {
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
创建并启动主机+服务:
public void StartWebService(object obj){
CreateWebHostBuilder();
host.StartAsync();
}
停止和处理服务和主机:
public void StopWebService(object obj) {
host.StopAsync().Wait();
host.Dispose();
}
因此,如果有人有任何建议或教程参考,请务必告诉我,欢迎任何帮助。
【问题讨论】:
标签: asp.net-web-api memory-leaks self-host-webapi corewcf