简体   繁体   中英

c# Dependency Injection cannot convert lambda to intended delegate

Cannot convert lambda to intended delegate because some of the return types in the block are not implicitly converted to the delegate return type.

without DI

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

ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);

with DI in Startup.cs

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

how do i make it so it's convertible and pass the correct options to the chromeDriver ?

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

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