作者:书友73277355 | 来源:互联网 | 2023-02-05 21:28
我有一个Service Fabric asp.net核心无状态服务,它实现了自定义中间件.在该中间件中,我需要访问我的服务实例.我将如何使用asp.net core的内置DI/IoC系统进行注入?
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext)
{
// ** need access to service instance here **
return _next(httpContext);
}
}
有人提到在2017年4月20日Q&A#11 [45:30]与Service Fabric团队一起使用TinyIoC在Web Api 2中完成此任务.同样,目前推荐的方法是使用asp.net核心.
任何帮助或示例将不胜感激!
1> Peter Bons..:
在创建的asp.net核心无状态服务中,ServiceInstanceListener
您可以像这样注入上下文:
protected override IEnumerable CreateServiceInstanceListeners()
{
return new[]
{
new ServiceInstanceListener(serviceCOntext=>
new WebListenerCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
{
logger.LogStatelessServiceStartedListening(url);
return new WebHostBuilder().UseWebListener()
.ConfigureServices(
services => services
.AddSingleton(serviceContext) // HERE IT GOES!
.AddSingleton(logger)
.AddTransient())
.UseContentRoot(Directory.GetCurrentDirectory())
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseStartup()
.UseUrls(url)
.Build();
}))
};
}
您的中间件可以像这样使用它:
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext, StatelessServiceContext serviceContext)
{
// ** need access to service instance here **
return _next(httpContext);
}
}
有关完整示例,请查看此存储库:https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring
您的兴趣点:
设置DI:https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring/blob/master/src/WebApi/WebApi.cs
在中间件中使用上下文:https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring/blob/master/src/ServiceFabric.Logging/Middleware/RequestTrackingMiddleware.cs