如何将依赖项注入到InvalidModelStateResponseFactory委托中?

huangapple go评论105阅读模式
英文:

How to inject dependency into InvalidModelStateResponseFactory delegate?

问题

public interface IErrorHandlingService 
{
    MyErrorResponse ErrorResponse { get; }
    void AddRequestInformation(Guid trace, DateTime timestamp, string requestRoute);
    void AddError(MyCustomError error);
    bool HasErrors();
}

我有一个作用域服务,用来处理我的应用程序中的所有错误,以及我想要作为错误响应的一部分返回的附加信息。当错误被引发时,我将它们添加到这个服务中,并且由于它是作用域的,它会跟踪特定请求的所有错误,并允许我在代码的各个点忽略或返回它们。

我希望通过这个服务处理任何模型绑定错误,以保持我的错误响应的格式一致。我可能有点儿愚蠢地假设 InvalidModelStateResponseFactory 是一个委托,它将在单个请求失败模型绑定验证时调用,那么我应该如何将我的作用域错误处理程序传递给它,以便在该函数中使用它?这是否可能?

我的直觉是在 services.Configure<ApiBehaviorOptions>(...) 调用内部分配它,但我无法找到在其中访问我的服务的“正确”方法。

services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = (actionContext) =>
    {
        var errHandler = // ???

        var errors = actionContext.ModelState
            .Where(e => e.Value.Errors.Count > 0)
            .Select(e => e.Value);

        foreach (var error in errors)
        {
            errHandler.AddError(new MyCustomError()
            {
                // 任何内容
            });
        }

        return new BadRequestObjectResult(errors);
    };
});

请注意,你需要找到一种方法来获取 IErrorHandlingService 的实例并分配给 errHandler 变量,这取决于你的应用程序的依赖注入配置。

英文:

I have a Scoped service that handles all errors in my application, along with supplementary info I want to return as part of my error response. As errors are raised I add them to this service and as it is scoped it keeps track of all errors for a particular request and allows me to ignore or return them at various points in my code.

public interface IErrorHandlingService 
{
    MyErrorResponse ErrorResponse { get; }
    void AddRequestInformation(Guid trace, DateTime timestamp, string requestRoute);
    void AddError(MyCustomError error);
    bool HasErrors();
}

I want to handle any model binding errors via this service to keep the format of my error responses consistent. I've made the (possibly silly) assumption that InvalidModelStateResponseFactory is a delegate that would be called at the point of a single request failing the model binding validation, so how would I pass my scoped error handler to this in order to use it in the function? Is this possible?

My instinct is to assign it inside the services.Configure&lt;ApiBehaviorOptions&gt;(...) call but I can't work out the "right" way to access my service inside there.

services.Configure&lt;ApiBehaviorOptions&gt;(options =&gt;
{
    options.InvalidModelStateResponseFactory = (actionContext) =&gt;
    {
        var errHandler = // ???

        var errors = actionContext.ModelState
            .Where(e =&gt; e.Value.Errors.Count &gt; 0)
            .Select(e =&gt; e.Value);

        foreach (var error in errors)
        {
            errHandler.AddError(new MyCustomError()
            {
                // whatever
            });
        }

        return new BadRequestObjectResult(errors);
    };
});

答案1

得分: 1

我可以通过actionContext.HttpContext.RequestServices访问服务,所以在我上面示例中分配errHandler的那一行将是:

var errHandler = (IErrorHandlingService)actionContext.HttpContext.RequestServices.GetService(typeof(IErrorHandlingService));
英文:

Managed to find the answer before I'd even finished writing the question - I can access the services via actionContext.HttpContext.RequestServices so the line in my example above where I assign the errHandler would be:

var errHandler = (IErrorHandlingService)actionContext.HttpContext.RequestServices.GetService(typeof(IErrorHandlingService));

huangapple
  • 本文由 发表于 2023年6月5日 19:22:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定