C
C#4w ago
ToxicLuffy

Inject services into custom view handler

Hello all. I have to create a custom webview handler for out MAUI application, and I need to access some of our injected services within that handler. My question is, is it possible to achieve a constructor injection for custom handlers, or I need to resolve the services using the static application/service instance within my handler? Using the constructor injection the DI framework complains that: "A suitable constructor for type ‘X’ could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided." MauiProgram:
...
_ = builder.ConfigureMauiHandlers(handlers => handlers.AddHandler<CustomWebView, CustomWebViewHandler>());
...
builder.Services.AddSingleton<ISomeService, SomeService>();
...
...
_ = builder.ConfigureMauiHandlers(handlers => handlers.AddHandler<CustomWebView, CustomWebViewHandler>());
...
builder.Services.AddSingleton<ISomeService, SomeService>();
...
CustomWebViewHandler:
public class CrossPlatformWebViewHandler : WebViewHandler
{
private readonly ISomeService _someService;
public CustomWebViewHandler(ISomeService someService)
{
_someService = someService;
}
...
}
public class CrossPlatformWebViewHandler : WebViewHandler
{
private readonly ISomeService _someService;
public CustomWebViewHandler(ISomeService someService)
{
_someService = someService;
}
...
}
Am I missing something or is this not supported for handlers(yet)? Otherwise I can use the static instance to resolve the service, but I had hoped that I can avoid it, constructor injection feels right to me.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?