有可能有两个不同的服务实现,并根据传递给它的道具将特定的实现注入组件中吗?
我试图找到一个解决方案,而我所能找到的就是在构造函数中将所需的服务从服务提供者中提取出来,而我不想这样做。我在API Controller中做了类似的事情,它本质上是在注入服务层之前拦截请求,并根据请求参数注入正确的服务实现。
编辑:
本质上,在启动期间,我希望能够注入相同接口服务的2个实现。
builder.Services.AddScoped<IEmployeeService,EmployeeServiceA>();
builder.Services.AddScoped<IEmployeeService,EmployeeServiceB>();然后,在我的工作中,我会做这样的事情:
@inject IEmployeeService _employeeService;随着实际的实现被注入到组件中,基于参数被发送到组件中,而这些参数会被中间磨损截获。
发布于 2022-06-22 21:56:04
您需要从ServiceProvider中手动获取正确的服务,方法是注入IServiceProvider并在提供者上调用GetService。
注意:对于普通组件注入,不建议这样做,因为您在使用该服务时需要小心:您可以尝试在初始化它之前访问它。在下面的示例中,它在OnInitialized中不可用。
下面是一个简单通知服务的示例。
接口:
public interface INotificationService
{
public event EventHandler? Changed;
public void NotifyChanged(object? sender);
}两个班:
public class WeatherForecastNotificationService
: INotificationService
{
public event EventHandler? Changed;
public void NotifyChanged(object? sender)
=> this.Changed?.Invoke(sender, EventArgs.Empty);
}public class WeatherReportNotificationService
: INotificationService
{
public event EventHandler? Changed;
public void NotifyChanged(object? sender)
=> this.Changed?.Invoke(sender, EventArgs.Empty);
}注册为(作用域)服务:
builder.Services.AddScoped<WeatherForecastNotificationService>();
builder.Services.AddScoped<WeatherReportNotificationService>();获取服务的组件- ServiceTestComponent.razor:
@inject IServiceProvider serviceProvider
<div class="bg-info p-2 m-2">
<h3>ServiceTestComponent</h3>
<div class="p-3">
Type: @message
</div>
</div>
@code {
[Parameter] public object? Record { get; set; }
private INotificationService notificationService = default!;
private string message = string.Empty;
protected override void OnParametersSet()
{
if (this.Record is WeatherForecast)
{
var service = serviceProvider.GetService<WeatherForecastNotificationService>();
if (service is not null)
notificationService = service as INotificationService;
}
else
{
var service = serviceProvider.GetService<WeatherReportNotificationService>();
if (service is not null)
notificationService = service as INotificationService;
}
// simple bit of code to demo what actual service we have
if (notificationService is not null)
message = notificationService.GetType().Name;
}
}还有一个测试页面:
@page "/"
@page "/Index"
<h1>Hello</h1>
<ServiceTestComponent Record=this.record />
<div>
<button class="btn btn-primary" @onclick=ChangeType>Change Type</button>
</div>
@code
{
private object record = new WeatherForecast();
private void ChangeType()
{
if (record is WeatherForecast)
record = new WeatherReport();
else
record = new WeatherForecast();
}
}https://stackoverflow.com/questions/72719953
复制相似问题