Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core Middleware service dependent on current User

Tags:

asp.net-core

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!

like image 485
marvc1 Avatar asked Feb 12 '16 15:02

marvc1


People also ask

Can you name any built in middleware which you used in .NET Core?

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.

What happens when a terminal middleware is used in the request pipeline?

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.


1 Answers

Have you tried using context.RequestServices?

like image 106
weiran Avatar answered Sep 28 '22 05:09

weiran