![](/img/trans.png)
[英]In my Blazor server app, I have a problem when programming the rows of a table dynamically. What could be the problem?
[英]I have created a class to manage my session storage in a blazor server app however i am struggling to get my dependency injection to work properly
在我的program.cs
文件中,我正在注冊我的 class,如下所示:
builder.Services.AddScoped<SessionStorageService>(x => new SessionStorageService(x.GetService<ProtectedLocalStorage>(), x.GetService<ProtectedBrowserStorage>()));
但是,那
x.GetService<ProtectedBrowserStorage>())
總是 null 因為我收到此錯誤:
尚未注冊類型“Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.ProtectedBrowserStorage”的服務。
它應該是:
builder.Services.AddScoped<SessionStorageService>
(x => new SessionStorageService(x.GetService<ProtectedLocalStorage>(),
x.GetService<ProtectedSessionStorage>()));
但是你為什么要這樣做呢? 做什么的?
做就是了:
builder.Services.AddScoped<SessionStorageService>();
DI Container 將負責在服務的構造函數中創建和分配實例(構造函數注入):
public class SessionStorageService
{
private readonly ProtectedLocalStorage _protectedLocalStorage;
private readonly ProtectedSessionStorage _protectedSessionStorage;
public SessionStorageService(ProtectedLocalStorage protectedLocalStorage,
ProtectedSessionStorage protectedSessionStorage)
{
_protectedLocalStorage = protectedLocalStorage;
_protectedSessionStorage = protectedSessionStorage;
}
我建議您執行此操作:
[https://github.com/Blazored/SessionStorage/tree/main/src/Blazored.SessionStorage][1]
它工作正常,只需為 IServiceCollection 創建一個擴展,然后在 Startup.cs 上調用它
services.AddServerStorage()
擴展應該有這個方法。
public static IServiceCollection AddServerStorage(this IServiceCollection services) => AddServerStorage(services, null);
稱之為:
public static IServiceCollection AddServerStorage(this IServiceCollection services, Action<SystemTextJsonOptions> configure)
{
return services
.AddScoped<IJsonSerializer, SystemTextJsonSerializer>()
.AddScoped<IStorageProvider, ServerStorageProvider>()
.AddScoped<IServerStorageService, ServerStorageService>()
.AddScoped<ISyncServerStorageService, ServerStorageService>()
.Configure<SystemTextJsonOptions>(configureOptions =>
{
configure?.Invoke(configureOptions);
if (!configureOptions.JsonSerializerOptions.Converters.Any(c => c.GetType() == typeof(TimespanJsonConverter)))
configureOptions.JsonSerializerOptions.Converters.Add(new TimespanJsonConverter());
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.