我有一个 Service Fabric asp.net 核心无状态服务,它实现了自定义中间件。在那个中间件中,我需要访问我的服务实例。我将如何使用 asp.net core 的内置 DI/IoC 系统注入(inject)它?

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);
    }
}

有人在 Apr 20, 2017 Q&A #11 [45:30] 中与 Service Fabric 团队提到在 Web Api 2 中使用 TinyIoC 来完成此操作。同样,当前推荐的方法是使用asp.net core。

任何帮助或示例将不胜感激!

最佳答案

在创建 ServiceInstanceListener 的 asp.net 核心无状态服务中,您可以像这样注入(inject)上下文:

protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return new[]
        {
            new ServiceInstanceListener(serviceContext =>
                new WebListenerCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
                {
                    logger.LogStatelessServiceStartedListening<WebApi>(url);

                    return new WebHostBuilder().UseWebListener()
                                .ConfigureServices(
                                    services => services
                                        .AddSingleton(serviceContext) // HERE IT GOES!
                                        .AddSingleton(logger)
                                        .AddTransient<IServiceRemoting, ServiceRemoting>())
                                .UseContentRoot(Directory.GetCurrentDirectory())
                                .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
                                .UseStartup<Startup>()
                                .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
  • 关于azure - 如何将 Service Fabric 服务上下文注入(inject) asp.net core 中间件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43552441/

    10-16 16:41