【发布时间】:2022-01-24 12:44:23
【问题描述】:
应用程序是 Blazor Server,问题与 Scope in Middleware and Blazor Component 非常相似,但它已经很久没有活动了,我已经澄清了一些部分。
我编写了一个从当前请求中读取 cookie 的中间件。已通过InvokeAsync 注入了一个作用域服务(单例不适合,因为它是针对每个用户的),并使用来自 cookie 的值进行更新。相同的服务被注入到一个页面组件中,但不幸的是它不是同一个服务实例。
render-mode="Server" 和 render-mode="ServerPrerendered" 我都试过了。它们的行为与您预期的不同,但它与在中间件中创建的实例不同。在渲染模式 Server 中,服务被注入一次,而在渲染模式 ServerPrerendered 中,服务被注入两次,一次用于预渲染页面,一次用于交互页面.我的目标是在中间件中为请求注入相同范围的服务,以便也注入到页面组件中。这可能吗?
添加中间件的代码(有点简化但仍然是同样的问题)。因为我只对页面请求感兴趣,所以我添加了一些过滤:
app.UseWhen(
context =>
{
return (context.Request.Path.StartsWithSegments("/_content") ||
context.Request.Path.StartsWithSegments("/_framework") ||
context.Request.Path.StartsWithSegments("/_blazor") ||
context.Request.Path.StartsWithSegments("/images") ||
context.Request.Path.StartsWithSegments("/favicon.ico") ||
context.Request.Path.StartsWithSegments("/css")) == false;
}
, builder => builder.UseSettingsMiddleware());
添加范围服务:
public void ConfigureServices(IServiceCollection services)
{
/* all other services added before this */
services.AddScoped<IThemeService, ThemeService>();
}
中间件:
public class ThemeMiddleware
{
private readonly RequestDelegate _next;
private string _id;
public ThemeMiddleware(RequestDelegate next)
{
_next = next;
_id = Guid.NewGuid().ToString()[^4..];
}
public async Task InvokeAsync(HttpContext httpContext, IThemeService themeService)
{
var request = httpContext.Request;
string path = request.Path;
string theme = request.Cookies["App.Theme"];
Debug.WriteLine($"Middleware [{_id}]: Service [{themeService.GetId()}] | Request Path={path} | Theme={theme}");
if(string.IsNullOrEmpty(theme) == false)
{
themeService.SetTheme(theme);
}
await _next(httpContext);
}
}
服务:
public class ThemeService : IThemeService, IDisposable
{
string _theme = "default";
string _id;
string dateTimeFormat = "ss.fffffff";
public ThemeService()
{
_id = Guid.NewGuid().ToString()[^4..];
}
public void Dispose() { }
public string GetId() { return _id; }
public string GetTheme()
{
Debug.WriteLine($"ThemeService [{_id}]: GetTheme={DateTime.Now.ToString(dateTimeFormat)}");
return _theme;
}
public void SetTheme(string theme)
{
Debug.WriteLine($"ThemeService [{_id}]: SetTheme={DateTime.Now.ToString(dateTimeFormat)}");
_theme = theme;
}
}
组件(MainLayout.razor中也存在基本相同的代码):
@page "/"
@inject IThemeService ThemeService
@code {
protected override async Task OnInitializedAsync()
{
System.Diagnostics.Debug.WriteLine($"Index.razor: Service [{ThemeService.GetId()}]");
}
}
输出
render-mode=服务器
Middleware [399d]: Service [1f37] | Request Path=/ | Theme=dark
ThemeService [1f37]: SetTheme=00.5996142
MainLayout.razor: Service [4e96]
ThemeService [4e96]: GetTheme=01.0375910
Index.razor: Service [4e96]
render-mode=ServerPrerendered
Middleware [982d]: Service [5fa8] | Request Path=/ | Theme=dark
ThemeService [5fa8]: SetTheme=03.2477461
MainLayout.razor: Service [5fa8]
ThemeService [5fa8]: GetTheme=03.3576799
Index.razor: Service [5fa8]
MainLayout.razor: Service [d27c]
ThemeService [d27c]: GetTheme=03.9510551
Index.razor: Service [d27c]
服务 id 在预渲染请求中实际上是相同的,但在交互式请求中是不同的,后者才是重要的。关于如何前进的任何想法?
【问题讨论】:
-
不幸的是,您可能需要一种不同的方法。对于启动时所需的简单数据,显而易见的“简单”选项是将其作为参数传递给
App组件,该组件将作为 Blazor 服务器的基础进行渲染。这反过来又可以用于启动 Blazor 范围内的 ThemeService。 -
您也可以使用 JSInterop 直接在 Blazor 代码中读取 cookie。
-
请同时粘贴您的服务的依赖注入详细信息 - 它们是否注册为作用域等。
-
我用服务注册@aleksander_si 更新了帖子。如您所见,它被注册为范围,这很重要,因为信息是每个用户的。
-
@Andreas 检查我的回答是否有帮助。
标签: c# asp.net-core dependency-injection blazor blazor-server-side