我今天更新了一个项目到ASP.NET Core 2,我收到以下错误:
不能从singleton IActiveUsersService使用作用域服务IMongoDbContext
我有以下注册:
services.AddSingleton<IActiveUsersService, ActiveUsersService>();
services.AddScoped<IMongoDbContext, MongoDbContext>();
services.AddSingleton(option =>
{
var client = new MongoClient(MongoConnectionString.Settings);
return client.GetDatabase(MongoConnectionString.Database);
})
public class MongoDbContext : IMongoDbContext
{
private readonly IMongoDatabase _database;
public MongoDbContext(IMongoDatabase database)
{
_database = database;
}
public IMongoCollection<T> GetCollection<T>() where T : Entity, new()
{
return _database.GetCollection<T>(new T().CollectionName);
}
}
public class IActiveUsersService: ActiveUsersService
{
public IActiveUsersService(IMongoDbContext mongoDbContext)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
为什么DI无法使用该服务?一切都适用于ASP.NET Core 1.1.
我正在努力在 Blazor 服务器的类中注入服务 (AuthenticationStateProvider)。如果我在剃刀组件中执行此操作,则非常简单:
@inject AuthenticationStateProvider AuthenticationStateProvider
进而
private async Task LogUsername()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
ClientMachineName = $"{user.Identity.Name}";
}
else
{
ClientMachineName = "Unknown";
}
}
Run Code Online (Sandbox Code Playgroud)
但是我需要这样做,即在类中而不是在剃刀组件中检索经过身份验证的用户机器名称。
我试过例如:
[Inject]
AuthenticationStateProvider AuthenticationStateProvider { get; set; }
public async Task LogUsername()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
ClientMachineName = $"{user.Identity.Name}";
}
else
{
ClientMachineName = "Unknown";
}
}
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用。
任何帮助将非常感激。