C# 对gRPC服务的依赖注入

C# 对gRPC服务的依赖注入,c#,unit-testing,dependency-injection,grpc,C#,Unit Testing,Dependency Injection,Grpc,我在Visual Studio中使用Protobuff和.NET core创建了一个gRPC服务,我想测试该服务 该服务获得了一个构造函数: public ConfigService(ILogger<ConfigService> logger) { _logger = logger; } 如何向服务构造函数的第二个参数注入?以最简单的形式,您只需将依赖项添加到ConfigureServices方法中的IServiceCollection public void Config

我在Visual Studio中使用Protobuff和.NET core创建了一个gRPC服务,我想测试该服务

该服务获得了一个构造函数:

public ConfigService(ILogger<ConfigService> logger)
{
    _logger = logger;
}

如何向服务构造函数的第二个参数注入?

以最简单的形式,您只需将依赖项添加到
ConfigureServices
方法中的
IServiceCollection

public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc();
    services.AddScoped<IMyInterface, MyClassImplementingInterface>();
}
public void配置服务(IServiceCollection服务)
{
services.AddGrpc();
services.addScope();
}
这将在服务集合中注册您的依赖项,并使其能够通过构造函数注入自动注入。在您的测试中,您将自己注入它,就像您似乎意识到的一样


请参阅此链接以供参考:

创建接口的实现或模拟,并将其传递给测试下的主题显示测试以及您的问题所在在测试中您的意思是我可以自己创建服务实例吗?新的ConfigService(null,新的MyMock())?是的,差不多。您还可以查看一个模拟框架(例如moq:),它将帮助您模拟依赖项。
 public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGrpcService<ConfigService>();

            endpoints.MapGet("/", async context =>
            {
                await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
            });
        });
    }
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc();
    services.AddScoped<IMyInterface, MyClassImplementingInterface>();
}