azure - 如何将Service Fabric服务上下文注入(inject)到asp.net core中间件中?

标签 azure asp.net-core azure-service-fabric

我有一个 Service Fabric asp.net core 无状态服务,它实现了自定义中间件。在该中间件中,我需要访问我的服务实例。我如何使用 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 中提到在 Web Api 2 中使用 TinyIoC 来完成此操作[45:30] 与 Service Fabric 团队合作。目前推荐的方法是使用asp.net core。

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

最佳答案

在创建 ServiceInstanceListener 的 asp.net core 无状态服务中,您可以像这样注入(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

您的兴趣点:

关于azure - 如何将Service Fabric服务上下文注入(inject)到asp.net core中间件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43552441/

相关文章:

azure - Elastica搜索结果未得到处理

azure - 如何在另一个部署中重用 terraform 输出值

.net - VS 2015 中未解决 Microsoft.NETCORE.app 依赖关系

c# - 如何在 Visual Studio ASP.NET Core Web 项目中每次重建时使 Kestrel 控制台窗口自动关闭/重置?

msbuild - 如何在sfproj上使用MSBuild?

sql-server - Azure SQL 托管实例 - 不支持创建凭据

python - Azure 应用服务无法在嵌套文件夹中找到 Flask 应用程序。即使有 GUnicorn

javascript - XMLHttpRequest 无法加载 No 'Access-Control-Allow-Origin' > 请求的资源上存在 header

c# - Service Fabric 服务调试问题

azure - 如何将持续运行的应用程序部署到 Azure Service Fabric?