[DotvvmStartup] How to inject custom service into custom ExceptionFilterAttribute class

Hi,

I have these:


And

And it fails like this:

How can I use my sessionToolbox inside OnCommandExceptionAsync() ?

PS:
I also want to set session entry
image

Unfortunately, dependency injection does not work into the DotvvmStartup class, since it can also configure service container itself. You have to explicitly call config.Services.GetRequiredService<SessionToolbox>() to obtain the service you want to pass to the action filter.

1 Like

It crashes the app with this:

‘Cannot resolve scoped service ‘NGM.Services.SessionToolbox’ from root provider.’

Am I calling it wrong or missing something? I already tried adding SessionToolbox as transient/scoped/singleton service in Program.cs (.NET 8 web app).

PS:

I can also obtain the service in Program.cs:
image

I got it to work.

For some reason (that I don’t understand), apart from the “GetRequiredService” line, I needed to also add services in ConfigureServices() of DotvvmStartup.cs:
image

The attribute will be a singleton, so it will break if you service is stateful. I think you should either make the service singleton too, or call GetRequiredService inside the attribute method — then even Scoped should work fine.

1 Like