簡體   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