3 questions on Microsoft.Extensions.Hosting #91375
Replies: 1 comment
-
When a service's constructor is called, it could be passed enough state such as a URL to perform an async http request itself. Also see
Some approaches: a service class can be declared using open generics (which can be closed at runtime) and the new "keyed services" feature in v8 can help when using System.Type as a service key isn't sufficient (a string can be used to identify a service for example).
Yes the IServiceProvider is automatically registered and can be injected.
I would avoid having the service hold the actual "business logic state" directly; such state should be passed to the service's constructor and the classes containing that state should be designed to be used inside or outside of DI. However, this choice is dependent on many factors including the application's design, existing code, etc. so it's not possible to provide a simple answer. I recommend looking at DI documentation and external docs\books on best practices and anti-patterns. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I am using Microsoft DI in a customer project.
Just to give you more context, the project is an Avalonia app, where I configure the DI manually, as follow:
Now, I would have a few questions about Microsoft DI:
The biggest issue I have, is that some services implementations would not be immediately available during app creation and initialization.
For example they would have dependencies on resources (http / server connections, and so on) not immediately available.
Or the instances could require additional parameters in the constructor, not immediately available during object creation.
But from my understanding, services are registered in the IServiceCollection at the builder phase.
After the Host is started, I don’t find ways to register services (in my case, with custom created instances, that receive these additional parameters).
Do I miss something, or are there way to avoid this limitation?
Another point is request for confirmation: if in a service I need DI, I can simply inject the IServiceProvider in the constructor.
I don’t need to register it, but anyway it will be available.
Final question: in case I need to represent state (think for example at the state of a machine, that is single and must be updated constantly), I would register a singleton as a service.
In this case, what is the best way to implement the service: with the classic Singleton pattern (private constructor, Instance get property, and so on) o register a normal class and use it through the singleton?
Beta Was this translation helpful? Give feedback.
All reactions