Peter
Peter

Reputation: 41

Blazor DI – How to access a service in a class that is not a Blazor component?

I have a background class that is not a Blazor component, and I want to use the built-in logger (ILogger) service.

I can’t use “[Inject]” on a property (because it’s not a component), and I can’t use the supported constructor injection because the constructor has other parameters (i.e. not just the single ILogger parameter). I have looked for something like “Application.GetService” (similar to what I've used other IOC implementations) that I could use in the constructor but can’t find anything.

Any ideas?

Upvotes: 2

Views: 1084

Answers (1)

Carl
Carl

Reputation: 1832

It looks like you need to register the default values for your service. You can do it in Startup.cs and in ConfigureServices something like services.AddTransient(<your service>).

If you want to be able to get a service at runtime, you can either inject an IServiceProvider with it's .GetService<>() method, or if you want to be able to call it without DI you can create a singleton that you register when your app starts up. The singleton will have a property for the service provider that you can then call from whatever service you would like (although I'd recommend against this - rather use DI)

It's also possible to combine the MS DI with other DI containers via an adapter. It seems that you already have a DI solution for your service, and this may be the best way forward if that's the case. In your CreateHostBuilder() setup method start with a .UseServiceProviderFactory() to use a different container. You'll need to find the correct adapter for your container though

Upvotes: 1

Related Questions