C
C#2y ago
Becquerel

Dependency injection - transient services inside a singleton?

I'm in Monogame (not my choice) and using DI to resolve various services I need, including those that represent user-facing screens. These screens live inside a big game-loop class that lives for the lifetime of the app. I want those screens to be refreshed every time they're activated. Currently I have them set up with a standard constructor that takes in their dependencies and an Initialize() method that refreshes their state. I'd rather be able to get the screens constructed from fresh each time they're needed. What's a good pattern for doing this? It seems analogous to making viewmodels in WPF-style frameworks. What I did there was pass around Func<MyViewModel>s, which pointed at the provider's GetRequiredService<MyViewModel() call to ensure all the dependencies were injected correctly. However, that doesn't seem like a particularly nice solution either. Is there a good way to do this? If I setup my views as transient services, injecting them into a singleton will just capture them, right?
4 Replies
Pobiega
Pobiega2y ago
Injecting them will indeed capture. The standard approach is to inject the service provider itself and resolve as needed
Becquerel
Becquerel2y ago
hm, that seems a bit dirty - service locator? but if it's the best solution that's what i'll do
Pobiega
Pobiega2y ago
You could set up a factory for the transient objects and inject the factory into your singleton, maybe?
devhl
devhl2y ago
Either inject a factory or an IServiceScopeFactory to get the CreateScope method. Actually, since you prob want to dispose the scope you may only want the later.