c# - 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 的实现。
解决方案
推荐阅读
- mysql - MVC 在绑定到数据库的 Razor DropdownlistFor 中设置默认值
- python - 从计算机读取多个 .wav 文件并将它们合并到 numpy 数组
- javascript - GetSelectedRangeS 是否存在?Excel OfficeJS API
- react-native - undefined 不是一个对象(评估 'this.refs.loaderRef.hide')
- xamarin.forms - 需要时如何在编辑器上隐藏键盘
- c# - C# SerialPort - RS485 如何在一个部分中接收所有数据
- apache-spark - 是否可以在 Zeppelin 段落中看到一些错误输出?
- android - java.lang.Exception:在类 android.app.Activity 上解析方法 startActivityForResult 失败
- java - Cacheable 和 jUnit,看起来 first 被忽略了
- c++ - 未调用由 signal() 指定的处理程序