在我的.Net6 Web应用程序中,我try 为单个IWordRepository接口的两个实现注册服务注入:

  1. WordRepositoryInMemory,处理内存中的数据;
  2. WordRepositoryDatabase个,用于调用数据库;

按照this article中的示例,我创建了一个枚举:

public enum WordRepositoryImplementation
{
    WordRepositoryInMemory,
    WordRepositoryDatabase
}

然后,在我的Program.cs美元里,我注册了这两项服务:

builder.Services.AddScoped<WordRepositoryDatabase>();
builder.Services.AddScoped<WordRepositoryInMemory>();

builder.Services.AddTransient<Func<WordRepositoryImplementation, IWordRepository?>>(wordRepositoryProvider => key =>
{
    return key switch
    {
        WordRepositoryImplementation.WordRepositoryInMemory => wordRepositoryProvider.GetService<WordRepositoryInMemory>(),
        WordRepositoryImplementation.WordRepositoryDatabase => wordRepositoryProvider.GetService<WordRepositoryDatabase>(),
        _ => null,
    };
});

然后,我在控制器中调用它,如下所示:

private readonly IWordRepository _wordRepositoryDatabase; // I only require one of the implementations to be called by this controller.

public DictionaryDataController(Func<WordRepositoryImplementation, IWordRepository> serviceResolver)
{
    _wordRepositoryDatabase = serviceResolver(WordRepositoryImplementation.WordRepositoryDatabase);
}

不幸的是,这增加了复杂性,搞砸了我对控制器的测试.我不再能够使用WordRepositoryDatabase服务中的简单Mock.Object来实例化sut.说不能,我的意思是,我还没有处理代表所需的经验.

在我的测试装置中,我try 替换服务的原始模拟实现:

private Mock<IWordRepository> _wordRepository;
// ....
_wordRepository= new Mock<IWordRepository>();
// ....
DictionaryDataController sut = new(_wordRepositoryDatabase.Object);

设置为返回IWordRepository的Mock的值,以便我可以在构造函数中使用它:

private Func<WordRepositoryImplementation, IWordRepository?> _funcWordRepositoryImplementation;
// ...
// ...
DictionaryDataController sut = new(_funcWordRepositoryImplementation);

然而,我在这里无法掌握所需的语法.我最接近的是一个返回Mock.Object的无参数Func&lt;&gt;(),但它显然遗漏了一些东西.

_funcWordRepositoryImplementation= () =>
{
    return new Mock<WordRepositoryImplementation, IWordRepository>();
};

而试图将一些参数传递给它导致了他们自己的一系列错误.

What would the correct way to set up this field be?

推荐答案

只需使用带有discard参数的lambda expression,它将返回_wordRepositoryDatabase.Object:

DictionaryDataController sut = new(_ => _wordRepositoryDatabase.Object);

Csharp相关问答推荐

System.Data.SQLite:判断SQLite数据库是否为空(任何表中至少有一行)

为什么在GuardationRule的收件箱函数中,decode.TryParse(valueString,out valueParsed)在给出1.0.1时返回true?

C#类主构造函数中的调试参数

LINQ无法翻译SQLFunctions方法

如何在Reflection. Emit中使用具有运行时定义的类型参数的泛型类型

编写DataAnnotations自定义验证器的多种方法

此反射有什么问题.是否发送值转换委托?

如何在没有额外副本的情况下将存储在IntPtr下的原始图像数据写入WinUI3中的Image控件?

发布用于Linux Ubuntu的C#应用程序

MS Graph v5.42.0:在寻呼消息时更改页面大小

附加标题不起作用,而添加则起作用

在.NET 7.0 API控制器项目中通过继承和显式调用基类使用依赖项注入

Swagger没有显示int?可以为空

异步任务调用程序集

如何对特定异常使用Polly重试机制?

Visual Studio,Docker容器-容器调用:连接被拒绝

如何从原始图像到新创建的图像获得相同的特定 colored颜色 ,并且具有相同的 colored颜色 量和相同的宽度和高度?

使用postman 测试配置了身份的.NET 6应用程序

SqlException:无法打开数据库.升级到Dotnet 8后-数据库兼容性版本-非EFCore兼容性级别

为什么我不能在固定语句中使用外部函数?