依赖注入:根据环境调用不同的服务

Fab*_*bio 1 c# inversion-of-control .net-core

我正在构建一个 .net core 3.1 Web 应用程序,并且正在尝试内置依赖项注入。

我想根据应用程序运行的运行时环境注入不同的服务,我认为我可以使用一个属性来定义该服务是否适合该环境,例如:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddTransient<IOperation, OperationDevelopment>();
    services.AddTransient<IOperation, OperationStaging>();
    services.AddTransient<IOperation, OperationProduction>();

    ...
}


public interface IOperation
{
    Guid OperationId { get; }
}

[Development]
public class OperationDevelopment : IOperation
{
}

[Staging]
public class OperationStaging : IOperation
{
}

[Production]
public class OperationProduction : IOperation
{
}
Run Code Online (Sandbox Code Playgroud)

我该怎么办,跳过注册?全部注册然后解决合适的服务?我错过了什么吗?

如果.net core DI太基础了,我应该使用什么?

谢谢

Dei*_*kis 5

您可以在方法内使用简单的 if 吗?希望能帮助到你

if (Environment.IsDevelopment())
{ 
    services.AddTransient<IOperation, OperationDevelopment>();
}
else
{
    services.AddTransient<IOperation, OperationProduction>();
}
Run Code Online (Sandbox Code Playgroud)