Help with dependency injection #17576
Replies: 1 comment
-
If you want a really detailed guide, Microsoft has their own. But it's mainly orientated around using it with ASP Core, so not all of it applies to using it with something like Avalonia. https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-basics
The MSDI approach is actually to just register multiple implementations of the same service, then change your constructor to accept an IEnumerable of them. That way it will just pass all of them in for you. If you don't use the IEnumerable, it will just pass the first one in.
Register your child view models as services, and then inject them into your main view model. The DI system builds up a whole dependency tree and works out what services need access to other services. The result is you don't really have to think about passing services around, you just need to make sure they are registered. If you have never used DI before, it can take awhile to understand how to use it properly especially since it's kind of backwards from the normal C# way of doing things. |
Beta Was this translation helpful? Give feedback.
-
Hi,
This is my first time working with dependency injection. I added Microsoft.Extensions.DependencyInjection to my Avalonia desktop project. I followed the quick Avalonia reference on DI here: https://docs.avaloniaui.net/docs/guides/implementation-guides/how-to-implement-dependency-injection
I have two questions
Basically the app is supposed to control a physical switching device. I created a class called 'InstrumentService' that represents a single instance of that switching device. But a user may have more than one switch device connected to their computer, so the app needs to be able to let the user select the device of interest and then it will display that device's info. So there may be multiple instances of 'InstrumentService' in existance, and the app should select the one that's needed.
So I was thinking that I should have a List and that this should be 'registerted' so that the ViewModels will have access to it.
I have a MainViewModel which instantiates a bunch of sub-ViewModels as shown below. The sub-ViewModels need to also have access to the resgistered service (List of InstrumentService)
Below is my Main View Model:
I created this class per the Avalonia document:
Then I did this in App.axaml.cs:
But how can I access this from the various sub-ViewModels? i.e. how can they access the list of InstrumentService?
Thanks
Beta Was this translation helpful? Give feedback.
All reactions