如何将Service Fabric服务上下文注入asp.net核心中间件?

rkt*_*ect 3 azure-service-fabric asp.net-core

我有一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有人提到在2017年4月20日Q&A#11 [45:30]与Service Fabric团队一起使用TinyIoC在Web Api 2中完成此任务.同样,目前推荐的方法是使用asp.net核心.

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

Pet*_*ons 6

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

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();
                }))
        };
    }
Run Code Online (Sandbox Code Playgroud)

您的中间件可以像这样使用它:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关完整示例,请查看此存储库:https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring

您的兴趣点: