Tewr / BlazorWorker

Library for creating DotNet Web Worker threads/multithreading in Client side Blazor
MIT License
392 stars 36 forks source link

IoC example #113

Open franko-tujani-dev opened 4 months ago

franko-tujani-dev commented 4 months ago

I am trying to use the worker service to delegate a few long running tasks in a background thread after a http response is returned, however i have a major issue with initialization.

What i am trying to do is create a background worker of a service type and that service has multiple dependencies that would usually be retrieved from the IServiceProvider. However i cannot understand how to inject the IServiceProvider in any way using the usual dependency injection container.

Tewr commented 4 months ago

I'll try to summarize the example code more or less in the order I would code them.

So in addition to your service you need a "startup service". Instead of a normal service proxy. And then you use this instance to spawn new instances using IoC. You have the example of such a startup service here: https://github.com/Tewr/BlazorWorker/blob/main/src/BlazorWorker.Demo.IoCExample/MyServiceStartup.cs

This is where you would call your usual extension methods like in asp.net Startup.ConfigureServices(). In the example the corresponding method is MyServiceStartup.Configure

Your service (in the example, https://github.com/Tewr/BlazorWorker/blob/main/src/BlazorWorker.Demo.IoCExample/MyIocService.cs), should just declare its dependencies as usual with IServiceProvider and it's friends. In the example it is using the constructor to reference its dependencies, like IMyServiceDependency

finally, the setup from your service proxy, the most simple is the one-liner described in https://github.com/Tewr/BlazorWorker/blob/main/src/BlazorWorker.Demo/SharedPages/Pages/IoCExamplePage.razor :

myIocService = await worker.CreateBackgroundServiceUsingFactoryAsync<MyServiceStartup, MyIocService>(startup => startup.Resolve<MyIocService>());

you can do this in two steps like shown in the example if you have several different service proxys to instantiate (it will be more efficient to reuse a startup service), or if you want to dispose services after each use.

Does that help you?