Blazor dependency injection in helper class #26357
-
I'm building a helper class for some of my components, that wraps an external JS library. This class doesn't need to be a component itself, but it needs to be instantiated by each component needing to use the JS lib. I can't figure out how to gain access to the IJSRuntime service within the helper class. Constructor DI doesn't seem to be working, nor is using the [Inject] parameter. I don't want to manually pass IJSRuntime to the class because I don't want the components to be aware of internal implementation details such as reliance on IJSRuntime. I tried inheriting my helper class from ComponentBase, constructor DI still not working, but @Inject and [Inject] work ONLY if I place the element on the razor page. If I keep the element off the page and I tried to instantiate it with new, I'm not getting DI. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I'm afraid you have to, because otherwise how would it know which In general, the DI system doesn't hook into .NET's What you probably want to do is register your helper as a DI service itself. Then components that want to use the helper can |
Beta Was this translation helpful? Give feedback.
I'm afraid you have to, because otherwise how would it know which
IJSRuntime
to use? With dependency injection in general, there are multiple "scopes" representing different partitions of services. For example with Blazor Server, there are multiple concurrent users, and each one has a separateIJSRuntime
instance. To obtain a service instance, you need to request it from a particular scope. Components can do this because they are attached to a particular renderer that holds a reference to the scope.In general, the DI sy…