启动类:如何添加作用域服务和中间件

问题描述 投票:0回答:1

我正在尝试向请求添加correlationid,并在各处跟踪它们。

我在启动类中有以下几行:

services.AddScoped<ICorrelationIdGenerator, CorrelationIdGenerator>();
// ... other code
app.AddCorrelationIdMiddleware();

然后我有以下内容:

public class CorrelationIdGenerator : ICorrelationIdGenerator
{
    private string _correlationId = Guid.NewGuid().ToString();

    public string Get() => _correlationId;

    public void Set(string correlationId)
    {
        _correlationId = correlationId;
    }
}
public static IApplicationBuilder AddCorrelationIdMiddleware(this IApplicationBuilder applicationBuilder)
        => applicationBuilder.UseMiddleware<CorrelationIdMiddleware>();
public class CorrelationIdMiddleware
{
    private readonly RequestDelegate _next;

    public CorrelationIdMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context, ICorrelationIdGenerator correlationIdGenerator)
    {
        var correlationId = GetCorrelationId(context, correlationIdGenerator);
        AddCorrelationIdHeaderToResponse(context, correlationId);

        await _next(context);
    }

    private static StringValues GetCorrelationId(HttpContext context, ICorrelationIdGenerator correlationIdGenerator)
    {
        if (context.Request.Headers.TryGetValue(HttpHeaderConstants.CORRELATIONID, out var correlationId))
        {
            correlationIdGenerator.Set(correlationId);
            return correlationId;
        }
        else
        {
            return correlationIdGenerator.Get();
        }
    }

    private static void AddCorrelationIdHeaderToResponse(HttpContext context, StringValues correlationId)
    {
        context.Response.OnStarting(() =>
        {
            context.Response.Headers.Add(HttpHeaderConstants.CORRELATIONID, new[] { correlationId.ToString() });
            return Task.CompletedTask;
        });
    }
}

问题主要是破坏了现有的测试,我不知道如何修复它们。这些测试继承自

IntegrationTestBase<Startup>

我将以下行添加到

IntegrationTestBase<Startup>

services.AddScoped<ICorrelationIdGenerator, CorrelationIdGenerator>();

我期待它能发挥作用。

相反,我遇到了一堆在添加功能之前没有的错误,并且

无法使用范围服务

来自单例x。其中x是与新功能无关的数据库。

c# scope integration-testing startup
1个回答
0
投票

正如@Stuartd 在他的评论中所说,由于他们的直播时间,我想做的事情是不可能的。

解决方案:更改注入的单例

© www.soinside.com 2019 - 2024. All rights reserved.