This is probably a basic question, but I can't find a good reference.
I have a simple filter and it executes fine.
public class MyFilter: IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
}
public void OnActionExecuted(ActionExecutedContext context)
{
// this fails since my singleton service is not in the collection
context.HttpContext.RequestServices
.GetRequiredService<IConnectionMultiplexer>();
}
}
When the filter executes and I consult context.HttpContext.RequestServices, I only find services that were registered as scoped. Is it possible for me to get a service registered as a singleton (which is what my IConnectionMultiplexer is)?
What I'm trying to do is execute a DB lookup as part of the pipeline, to augment the response's headers with my customer headers. Alternatives welcome as well.
CodePudding user response:
You can create a constructor for the filter and can access the singleton service directly right?
builder.Services.AddSingleton<DemoService>();
builder.Services.AddScoped<CustomFilter>();
And in the filter.
public class CustomFilter : IActionFilter
{
private readonly DemoService _demoService;
public CustomFilter(DemoService demoService)
{
_demoService = demoService;
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
}