繁体   English   中英

对 gRPC 服务的依赖注入

[英]Dependency injection to a gRPC service

我在具有 .NET 核心的 Visual Studio 中使用 Protobuff 创建了一个 gRPC 服务,我想测试该服务。

该服务有一个构造函数:

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

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

public ConfigService(ILogger<ConfigService> logger, IMyInterface instance)
{
    _logger = logger;
    _myDepndency = instance;
}

并且在实际运行实例中将是new RealClass()但是在测试时很容易通过new MockClass()

启动 class 仍然是默认的:

 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");
            });
        });
    }
}

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

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc();
    services.AddScoped<IMyInterface, MyClassImplementingInterface>();
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM