.NET核心-注入不同的服务实现

时间:2019-10-22 07:27:01

标签: dependency-injection .net-core

使用.NET Core 2.2,我有一组服务可以调用SecurityService来执行授权检查(“用户是否已登录,并且他/她是否具有必需的权限?”)。我遇到的问题是,这些服务也由HostedService调用,该服务(1)没有登录用户,(2)不需要授权,因为它是具有完全权限的内部过程。

以另一种方式声明它:

  • ServiceA调用(通过DI)SecurityService
  • ServiceB调用(通过DI)SecurityService
  • HostedService调用(通过IServiceScopeFactory)ServiceA和ServiceB。

我的目标是让SecurityService在被ServiceA / B调用时(->执行授权检查)与在HostedService上调用(->不要执行执行授权检查)时的行为有所不同。我在想类似的东西:

services.AddScoped<IServiceA, ServiceAImpl>();
services.AddScoped<IServiceB, ServiceBImpl>();

services.AddScoped<ISecurityService, SecurityServiceImpl>(); // Implementatation that performs checks

services.AddHostedService<MyHostedService>( ??? => <ISecurityService, DifferentSecurityServiceImplThatDoesntCheckPermissions> ) 

以上可能吗?否则,是否需要为HostedService创建其他服务提供商,而该ServiceProvider可以访问相同的ServiceA和ServiceB但具有不同的SecurityService?

securedServiceCollection.AddScoped<IServiceA, ServiceAImpl>();
securedServiceCollection.AddScoped<IServiceB, ServiceBImpl>();
securedServiceCollection.AddScoped<ISecurityService, SecurityServiceImpl>();
ServiceProvider securedServiceProvider = ...

internalServiceCollection.AddScoped<IServiceA, ServiceAImpl>();
internalServiceCollection.AddScoped<IServiceB, ServiceBImpl>();
internalServiceCollection.AddScoped<ISecurityService, DifferentSecurityServiceImplThatDoesntCheckPermissions>();
internalServiceCollection.AddHostedService<MyHostedService>();
ServiceProvider unsecuredServiceProvider = ...

但是当我注入SecurityService时,将使用哪个ServiceProvider?我应该提供IServiceScopeFactory的自定义实现吗?但是我又该如何告诉HostedService使用特定的Provider / Factory?

0 个答案:

没有答案