通过中间件的有条件依赖注入。
是否可以根据传递给其的道具将服务的2种不同的实现并将特定的实现注入组件中?
我试图找到一个解决方案,而我所能找到的就是将所需的服务从我不想做的构造函数中拉出。我在API控制器中做了类似的操作,从本质上讲,在注入服务层并根据请求参数注入正确的服务实现之前,该请求将截取。
编辑:
从本质上讲,在启动期间,我希望能够注入相同接口服务的2个实现。
builder.Services.AddScoped<IEmployeeService,EmployeeServiceA>();
builder.Services.AddScoped<IEmployeeService,EmployeeServiceB>();
然后,在我的组件中,我会做类似的事情:
@inject IEmployeeService _employeeService;
将实际的实现注入到组件中,该组件基于将参数发送到组件中,该组件将被中型磨损拦截。
Is it possible to have 2 different implementations of a service and inject a specific implementation into a component based on the props passed to it?
I have tried to find a solution and all I could find is pulling the desired service out of the services provider in the constructor which I don't want to do. I have done something similar in an API Controller which essentially would intercept the request before the service layer was injected and inject the correct service implementation depending on the request parameters.
Edit:
Essentially during startup I want to be able to inject 2 implementations of the same interface service.
builder.Services.AddScoped<IEmployeeService,EmployeeServiceA>();
builder.Services.AddScoped<IEmployeeService,EmployeeServiceB>();
Then in my component I would do something like:
@inject IEmployeeService _employeeService;
With the actual implementation being injected into the component being decided based off of parameters being sent into the component which would be intercepted by middle wear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要通过在提供商上注入iserviceProvider并调用
getService
来手动从ServiceProvider获得正确的服务。注意:不建议对普通组件注射使用,因为您需要在使用服务时要谨慎:您可以在初始化之前尝试访问它。在下面的示例中,它在
on Initialized
中不可用。这是简单通知服务的示例。
接口:
两个类:
注册为(范围)服务:
获取服务的组件-ServiceTestComponent.Razor:
和一个测试页面:
You need to manually get the correct service from the ServiceProvider by injecting the IServiceProvider and calling
GetService
on the provider.Note: This is not recommended for normal component injection because you need to be careful about when you use the service: you may try and access it before you have initialized it. In the example below it's not available in
OnInitialized
.Here's an example for a simple notification service.
An interface:
Two classes:
Registered as (scoped) services:
A component to get the services - ServiceTestComponent.razor:
And a test page: