gRPC 服务的依赖注入

Yon*_*Nir 3 c# unit-testing dependency-injection grpc

我已经在带有 .NET core 的 Visual Studio 中使用 Protobuff 创建了一个 gRPC 服务,并且我想测试该服务。

该服务有一个构造函数:

public ConfigService(ILogger<ConfigService> logger)
{
    _logger = logger;
}
Run Code Online (Sandbox Code Playgroud)

就像以某种方式注入的 ILogger 一样(我不知道如何注入),我想注入一个附加参数 - 一个接口。这个接口应该在运行时很容易设置,因为我想在运行真实运行时设置某个类,在测试时设置模拟类。例如:

public ConfigService(ILogger<ConfigService> logger, IMyInterface instance)
{
    _logger = logger;
    _myDepndency = instance;
}
Run Code Online (Sandbox Code Playgroud)

在实际运行实例中会是这样new RealClass(),但是在测试时很容易通过new MockClass()

启动类仍然是默认的:

 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");
            });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Dag*_*geJ 8

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc();
    services.AddScoped<IMyInterface, MyClassImplementingInterface>();
}
Run Code Online (Sandbox Code Playgroud)

这将在服务集合中注册您的依赖项,并使其能够通过构造函数注入自动注入。在您的测试中,您将自己将其注入为您似乎意识到的模拟。

请参阅此链接以供参考:ASP.NET Core 中的依赖注入