简体   繁体   中英

Dependency injection to a gRPC service

I have created a gRPC service using Protobuff in Visual Studio with .NET core and I want to test the service.

The service got a constructor:

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

Like the ILogger which is somehow injected (and I have no idea how), I want to inject an additional parameter - an interface. This interface is supposed to be easily set during runtime since I want to set a certain class when running a real run and a mock class when testing. for example something like:

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

and that in a real run instance will be new RealClass() but when testing it'll be easy to pass new MockClass() .

The startup class is still the default:

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

How can I inject to the 2nd parameter of the constructor of the service?

In the simplest form you can just add your dependency to the IServiceCollection in the ConfigureServices method;

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

This will register your dependency in the service collection and enable it to be injected automatically through constructor injection. In your test you will inject it yourself as a mock as you seem to be aware of.

See this link for reference: Dependency injection in ASP.NET Core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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