Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IoC example #113

Open
franko-tujani-dev opened this issue Jul 2, 2024 · 1 comment
Open

IoC example #113

franko-tujani-dev opened this issue Jul 2, 2024 · 1 comment

Comments

@franko-tujani-dev
Copy link

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
Copy link
Owner

Tewr commented Jul 5, 2024

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?

@Tewr Tewr closed this as completed Jul 5, 2024
@Tewr Tewr reopened this Jul 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants