我使用.NET Core在Visual Studio中使用Protobuff创建了一个gRPC服务,想要测试一下该服务。
该服务有一个构造函数:
该服务有一个构造函数:
public ConfigService(ILogger<ConfigService> logger)
{
_logger = logger;
}
像ILogger一样,它被注入(我不知道如何注入),我想注入一个额外的参数 - 一个接口。这个接口应该可以在运行时轻松设置,因为我想在实际运行时设置特定的类,在测试时设置模拟类。例如:
public ConfigService(ILogger<ConfigService> logger, IMyInterface instance)
{
_logger = logger;
_myDepndency = instance;
}
在实际运行的情况下,对象将被创建为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");
});
});
}
}
我如何向服务的构造函数的第二个参数注入内容?