feat: working version with scopes.

This commit is contained in:
redglow
2026-07-18 12:09:43 +02:00
parent 23e160438f
commit 04f0b5ef16
15 changed files with 120 additions and 87 deletions
+3 -27
View File
@@ -1,6 +1,4 @@
using System;
using System.Linq;
using Godot;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OwofGames.GodotHost;
@@ -12,7 +10,7 @@ namespace GodotHostTest.GodotDI;
/// <summary>
/// The base class for a root scope. Implement this class and its abstract methods to kick off the DI system.
/// </summary>
public abstract partial class RootServiceSource : ServiceSource, ISceneInstantiator
public abstract partial class RootServiceSource : ServiceSource
{
private Host? _host;
@@ -28,28 +26,6 @@ public abstract partial class RootServiceSource : ServiceSource, ISceneInstantia
private ILogger<RootServiceSource> Logger => _logger ??= Host.GetLogger<RootServiceSource>();
/// <inheritdoc />
public Node Instantiate(PackedScene packedScene, Delegate? onScopeCreated = null)
{
var node = packedScene.Instantiate();
var scope = node.GetChildren().OfType<ServiceSource>().SingleOrDefault();
if (scope == null)
Logger.LogDebug(
"Instantiated the scene {PackedSceneName} through ISceneInstantiator.Instantiate, but no scope found.",
packedScene.GetName());
else
scope.ResolveInjectedNodes(Host.ServiceProvider, onScopeCreated);
return node;
}
/// <inheritdoc />
public T Instantiate<T>(PackedScene packedScene, Delegate? onScopeCreated = null)
where T : Node
{
return (T)Instantiate(packedScene, onScopeCreated);
}
public override void _EnterTree()
{
// create the host
@@ -59,12 +35,12 @@ public abstract partial class RootServiceSource : ServiceSource, ISceneInstantia
.Build();
// resolve nodes
ResolveInjectedNodes(Host.ServiceProvider, null);
ResolveInjectedNodes(Host.ServiceProvider.GetRequiredService<IProvider>(), null);
}
private void InnerConfigure(IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<ISceneInstantiator>(this);
serviceCollection.AddTransient<ISceneInstantiator, SceneInstantiator>();
ConfigureServices(serviceCollection);
}