C
C#•2y ago
Becquerel

Dependency injection, but critical resources are only available after building the service provider

I'm trying to introduce dependency injection to a monogame project. For those unaware, Monogame gives you a Game class with some crucial components (GraphicsDevice and ContentManager) for getting stuff drawn to the screen. These components are only initialized after you construct your Game instance and call .Run() on it, making it 'live'. So far I've been creating my service provider manually inside the Game class and using it as a faux-entry point. However, I really want to move the DI outside and resolve Game like anything else. This is mainly because it'll let me use proper async/await, which I currently can't do. I have a mix of UI services that rely on the Game components (GraphicsDevice etc.) and 'pure' backend services. I can't have separate service providers for backend and frontend services, because the frontend relies on the backend. Is there a way to 'add' services to an IServiceProvider after it's been built? Can give more detail as necessary.
7 Replies
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Becquerel
Becquerel•2y ago
I'm not sure - how do you mean
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Becquerel
Becquerel•2y ago
i'll consider it
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Becquerel
Becquerel•2y ago
heh that example is actually what's motivating this i want to add a hosted service to the project this doesn't let you get the stuff inside of Game into a container though i can get stuff injected into Game no problem, but not the opposite
Klarth
Klarth•2y ago
Maybe you can use a lazy initialization pattern instead, barring circular dependency issues. Register as singleton, pull it after provider is ready, and initialize parameters. 🤔 You might have the issue of constructing components before everything is setup though...which would be unfortunate.