【问题标题】:Is it possible in Blazor Server to inject scoped service in middleware and inject that same instance in component?在 Blazor Server 中是否可以在中间件中注入作用域服务并在组件中注入相同的实例?
【发布时间】: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


【解决方案1】:

我看到了类似的问题,并能够解决如下:

  1. 准备一个类似于下面的包装类:
public static class Wrapper<T>
{
    private static AsyncLocal<T> _value = new AsyncLocal<T>();

    public static T CurrentValue
    {
        get
        {
            return _value.Value;
        }
        set
        {
            _value.Value = value;
        }
    }
}
  1. 准备一个中间件:
public class TestMiddleware<T>: IMiddleware
{
    public virtual async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        Wrapper<T>.CurrentValue = /* set references */;

        await next(context);
    }
}
  1. 您现在可以从 Blazor 页面或在当前 Blazor 电路中实例化的范围/瞬态服务访问 Wrapper&lt;T&gt;.CurrentValue。

如果我通过查看源代码没记错的话,根本原因是 Blazor DI 范围是一个新实例,而不是中间件 DI 范围。

【讨论】:

  • 我尝试了你的建议@aleksander_si 但它不起作用,我怀疑这是由于不是相同的异步上下文或不是从相同的上下文产生的。它的行为基本上与初始代码完全相同。不过,我确实以更简单的方式实现了该功能,我会尽快更新帖子。
  • 还有一点需要注意——中间件的顺序很重要——你应该在映射端点之前添加它。请参阅我的建议的 WebApp 示例:github.com/akovac35/Logging.Samples
  • 是的,端点映射是最后要做的事情。
【解决方案2】:

我为最初的问题选择了另一种解决方案,即读取一个 cookie 值并将其用于组件级别的注入服务中。我本来希望将其作为中间件来处理,但不幸的是,除非使用单例服务,否则从未找到这样做的方法,这不是一个选项。

Startup.cs:

services.AddScoped<IThemeService, ThemeService>();

ThemeService.cs:

public class ThemeService : IThemeService, IDisposable
{
    string _id;
    string _theme = "default";
    string _themeCookieName;

    public ThemeService(IHttpContextAccessor contextAccessor, IOptions<MyConfiguration> myConfig)
    {
        _id = Guid.NewGuid().ToString()[^4..];
        _themeCookieName = myConfig.Value.ThemeCookieName;
        RetrieveTheme(contextAccessor);
    }

    void RetrieveTheme(IHttpContextAccessor contextAccessor)
    {
        var request = contextAccessor.HttpContext.Request;
        string theme = request.Cookies[_themeCookieName];
        if (string.IsNullOrEmpty(theme) == false)
        {
            _theme = theme;
        }
    }

    public void Dispose() { }

    public string GetId() { return _id; }

    public string GetTheme() { return _theme; }

    public void SetTheme(string theme) { _theme = theme; }
}

MainLayout.razor:

@inject IThemeService ThemeService

/* markup */

@code {
    bool _darkTheme = false;
    MudTheme _theme = new DefaultTheme();

    protected override async Task OnInitializedAsync()
    {
        var currentTheme = ThemeService.GetTheme();
        _darkTheme = currentTheme == "dark";
        _theme = _darkTheme ? new DarkTheme() : new DefaultTheme();
    }
}

【讨论】:

    猜你喜欢
    • 2017-04-16
    • 2020-06-25
    • 2013-06-30
    • 2017-10-25
    • 2016-08-08
    • 2018-07-05
    • 2016-11-05
    • 2017-01-17
    • 2020-01-29
    相关资源
    最近更新 更多