I would like to either change a request scoped service or set one in a custom middleware layer.
Specifically, I want to be able to do something like the below contrived example in Startup.cs
:
public void ConfigureServices(IServiceCollection service)
{
service.AddScoped<IMyUserDependentService>((provider) => {
return new MyService());
});
}
public void Configure(...) {
//other config removed
app.Use(async (context, next) => {
var myService = context.ApplicationServices.GetService<IMyUserDependentService>();
myService.SetUser(context.User.Identity.Name);//Name is Fred
next.Invoke();
});
}
Then in the controller do this:
public class HomeController: Controller
{
public HomeController(IMyUserDependentService myService)
{
//myService.UserName should equal Fred
}
}
The problem is, that this doesn't work. myService.UserName isn't Fred in controller, it's null. I think that the IOC container is creating a new instance in the controller, and not using the one set in the middleware.
If I change the scope of the service to Transient, Fred is remembered, but that doesn't help because the service is dependent on who the current user is.
To recap, what I need is to create/or edit a service that requires the current user (or other current request variables), but am unable to work this out.
Thanks in advance!
A middleware is nothing but a component (class) which is executed on every request in ASP.NET Core application. In the classic ASP.NET, HttpHandlers and HttpModules were part of request pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed in each request.
These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline.
Have you tried using context.RequestServices
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With