Код: Выделить всё
public class Service
{
private IPage? _page;
private readonly ScreenshotOptions _options;
public Service(IOptions options) => _options = options.Value;
public async Task CreateScreenshotAsync()
{
if (_page == null)
_page = await InitializePlaywrightAsync();
await _page.ScreenshotAsync(new PageScreenshotOptions { Path = _options.Filename });
// all the other stuff
}
private async Task InitializePlaywrightAsync()
{
var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
await page.SetViewportSizeAsync(_options.Width, _options.Height);
return page;
}
}
// Program.cs
builder.Services.AddSingleton();
Код: Выделить всё
public class Service
{
private IPage _page;
private readonly ScreenshotOptions _options;
public Service(IOptions options, IPage page)
{
_options = options.Value;
_page = page;
}
public async Task CreateScreenshotAsync()
{
await _page.ScreenshotAsync(new PageScreenshotOptions { Path = _options.Filename });
// all the other stuff
}
}
// Program.cs - compilation error
builder.Services.AddSingleton((IOptions options) =>
{
var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
await page.SetViewportSizeAsync(options.Width, options.Height);
return page;
});
builder.Services.AddSingleton();
Код: Выделить всё
public class PageFactory
{
private readonly ScreenshotOptions _options;
public PageFactory(IOptions options) => _options = options.Value;
public async Task InitializePlaywrightAsync()
{
var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
await page.SetViewportSizeAsync(_options.Width, _options.Height);
return page;
}
}
// Program.cs - compilation error
builder.Services.AddSingleton(async provider => await provider.GetRequiredService().InitializePlaywrightAsync());
Подробнее здесь: https://stackoverflow.com/questions/764 ... -container