From 9e45b4f390d60b60a7ba36e72cfc9e2e1b66efe9 Mon Sep 17 00:00:00 2001 From: cherrynik Date: Tue, 27 Feb 2024 18:37:41 +0300 Subject: [PATCH] fix(di): registered `GraphicsDeviceManager` on the same level with `Game` - Fixed double-disposing behaviour issue, when the game is quit (left a comment) --- .../CompositionRoots/GameCompositionRoot.cs | 33 ++++++++++--------- src/Apps/GameDesktop/Program.cs | 4 ++- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/Apps/GameDesktop/CompositionRoots/GameCompositionRoot.cs b/src/Apps/GameDesktop/CompositionRoots/GameCompositionRoot.cs index 79f7a85..149b825 100644 --- a/src/Apps/GameDesktop/CompositionRoots/GameCompositionRoot.cs +++ b/src/Apps/GameDesktop/CompositionRoots/GameCompositionRoot.cs @@ -2,8 +2,6 @@ using GameDesktop.Resources.Internal; using LightInject; using Microsoft.Xna.Framework; -using MonoGame.ImGuiNet; -using Myra; using Serilog; namespace GameDesktop.CompositionRoots; @@ -16,21 +14,24 @@ internal class GameCompositionRoot : ICompositionRoot public void Compose(IServiceRegistry serviceRegistry) { - serviceRegistry.RegisterSingleton(factory => + ServiceRegistration[] services = serviceRegistry.AvailableServices.ToArray(); + + var logger = + (ILogger)services.First(r => r.ServiceType == typeof(ILogger)).Value; + var container = + (IServiceContainer)services.First(r => r.ServiceType == typeof(IServiceContainer)).Value; + + Game game = new(logger, container) { - Game game = new(factory.GetInstance(), - factory.GetInstance()) - { - IsMouseVisible = IsMouseVisible, - IsFixedTimeStep = IsFixedTimeStep, - Content = { RootDirectory = AppVariable.ContentRootDirectory, }, - }; + IsMouseVisible = IsMouseVisible, + IsFixedTimeStep = IsFixedTimeStep, + Content = { RootDirectory = AppVariable.ContentRootDirectory, }, + }; + serviceRegistry.RegisterInstance(game); - // Hack. Resolving cycle dependency issue (fundamental architecture) - // Implicitly adds itself in the game services container. - new GraphicsDeviceManager(game); - - return game; - }); + // Hack. Resolving cycle dependency issue (fundamental architecture) + // Implicitly adds itself in the game services container. + GraphicsDeviceManager graphicsDeviceManager = new(game); + serviceRegistry.RegisterInstance(graphicsDeviceManager); } } diff --git a/src/Apps/GameDesktop/Program.cs b/src/Apps/GameDesktop/Program.cs index d71d38a..5bd402b 100644 --- a/src/Apps/GameDesktop/Program.cs +++ b/src/Apps/GameDesktop/Program.cs @@ -19,7 +19,9 @@ try { - using ServiceContainer container = new( + // "Using" keyword should be used either with the container, or with the game instance. + // Otherwise, you'll get the double-disposing behaviour. + ServiceContainer container = new( new ContainerOptions { EnablePropertyInjection = false,