C#依赖注入无法将Lambda转换为预期的委托

时间:2018-07-25 01:45:21

标签: c# asp.net-core lambda dependency-injection

无法将lambda转换为预期的委托,因为该块中的某些返回类型并未隐式转换为委托的返回类型。

没有DI

var chromeDriverService = ChromeDriverService.CreateDefaultService();
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments(new List<string>() { "headless" });

ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);

在Startup.cs中带有DI

 services.AddScoped<ChromeDriverService>((serviceProvider =>
 {
   return  ChromeDriverService.CreateDefaultService();
 }));
 //**** errors here*****
 services.AddScoped<ChromeOptions>((serviceProvider =>
 { return new ChromeOptions().AddArguments(new List<string>() { "headless" }); }));
 // errors here******
 // how would i pass the driver service & options 
 services.AddScoped<ChromeDriver>(
 (serviceProvider =>
 {
   return new ChromeDriver(chromeDriverService,chromeOptions);
 }));

我如何使其可转换并将正确的选项传递给chromeDriver?

1 个答案:

答案 0 :(得分:3)

You have an issue within this line:

services.AddScoped<ChromeOptions>((serviceProvider =>
{ return new ChromeOptions().AddArguments(new List<string>() { "headless" }); }));

AddScoped input delegate is excepted to return ChromeOptions while .AddArguments returns void

How about:

services.AddScoped<ChromeOptions>((serviceProvider =>
{
    var chromeOptions = new ChromeOptions();
    chromeOptions.AddArguments(new List<string>() {"headless"});
    return chromeOptions; // Return expected type
});

services.AddScoped<ChromeDriver>((s => 
{
     return new ChromeDriver(s.GetService<ChromeDriverService>(), 
                             s.GetService<ChromeOptions>());
}));