我想更改请求范围服务或在自定义中间件层中设置一个。
具体来说,我希望能够在 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();
});
}
然后在 Controller 中执行以下操作:
public class HomeController: Controller
{
public HomeController(IMyUserDependentService myService)
{
//myService.UserName should equal Fred
}
}
问题是,这行不通。 myService.UserName 不是 Controller 中的 Fred,它是 null。我认为 IOC 容器正在 Controller 中创建一个新实例,而不是使用中间件中设置的实例。
如果我将服务范围更改为 Transient,则会记住 Fred,但这无济于事,因为该服务取决于当前用户是谁。
回顾一下,我需要的是创建/或编辑需要当前用户(或其他当前请求变量)的服务,但我无法解决这个问题。
提前致谢!
最佳答案
您是否尝试过使用 context.RequestServices
?
关于asp.net-core - 依赖于当前用户的 Asp.Net Core Middleware 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35365851/