首页 > 解决方案 > C# - .NET Core - 范围的依赖注入更改实现

问题描述

是否可以针对特定范围更改接口的实现?我想要的是“ILogService”的默认实现,它将数据记录到磁盘。但是对于任务调度程序,我使用“IServiceScopeFactory.CreateScope()”来解决任务的实现,但在这种情况下,我想使用不同的实现来记录日志,因此数据最终会出现在我的数据库中。

interface ILogService { void Write(string text); }

这有一个默认实现

class LogDisk : ILogService { void Write(string text) { ... } }

但是当我在类 x 使用 ILogService 的范围内执行 GetService() 时,我想使用它

class LogTask : ILogService { void Write(string text) { ... } }

是否可以针对特定范围更改接口的实现?

例子

public class TaskFactory : ITaskFactory
{
    private IServiceScopeFactory _serviceScopeFactory;

    public TaskFactory(IServiceScopeFactory serviceScopeFactory)
    {
        this._serviceScopeFactory = serviceScopeFactory;
    }

    public ITaskDefinition GetDefinition(ETaskType taskType)
    {
        using (var scope = this._serviceScopeFactory.CreateScope())
        {
            var provider = scope.ServiceProvider.GetService<ITaskX>();
            return null;
        }
    }
}

在任务中,如果我应该使用实现 A 或 B,我不想看看应该如何实现。每个任务都有自己的依赖关系,这就是我希望依赖注入来处理的问题。但我想更改的唯一实现是 ILogService 的实现。

标签: c#.netdependency-injection.net-core

解决方案


推荐阅读