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 -1
View File
@@ -14,6 +14,8 @@ public partial class GameServiceSource : RootServiceSource
builder builder
.AddSingleton<ICurrentLevel, CurrentLevel>() .AddSingleton<ICurrentLevel, CurrentLevel>()
.AddInstance<ILevelDataProvider, LevelsData>(_levelsData) .AddInstance<ILevelDataProvider, LevelsData>(_levelsData)
.AddValueProvider<ILevel, RootScope, LevelScope>(); .AddValueProvider<ILevel, RootScope, LevelScope>()
.AddValueProvider<ITargetCollector, LevelScope>()
.AddValueProvider<ITargetSpawner, LevelScope>();
} }
} }
+7 -6
View File
@@ -1,5 +1,7 @@
using Godot; using Godot;
using GodotHostTest.GodotDI; using GodotHostTest.GodotDI;
using GodotHostTest.Interfaces;
using OwofGames.GodotLume;
namespace GodotHostTest.Game; namespace GodotHostTest.Game;
@@ -7,10 +9,9 @@ public partial class LevelServiceSource : ServiceSource
{ {
[Export] private TargetSpawner _targetSpawner = null!; [Export] private TargetSpawner _targetSpawner = null!;
// protected override void ConfigureServices(IServiceCollection serviceCollection) protected override void OnScopeCreated(IProvider serviceProvider)
// { {
// serviceCollection serviceProvider.Get<IValueSetter<ITargetCollector>>().Set(_targetSpawner);
// .AddSingleton<ITargetCollector>(_targetSpawner) serviceProvider.Get<IValueSetter<ITargetSpawner>>().Set(_targetSpawner);
// .AddSingleton<ITargetSpawner>(_targetSpawner); }
// }
} }
+1 -1
View File
@@ -10,7 +10,7 @@ public partial class LevelsData : Resource, ILevelDataProvider
public ILevel GetLevelData(int levelNumber) public ILevel GetLevelData(int levelNumber)
{ {
var entry = _levelDataEntries[levelNumber]; var entry = _levelDataEntries[levelNumber - 1];
return entry; return entry;
} }
} }
+2 -2
View File
@@ -10,12 +10,12 @@ namespace GodotHostTest.Game;
public partial class Projectile : Node2D public partial class Projectile : Node2D
{ {
[Inject] private readonly ILogger<Projectile> _logger = null!; [Inject] private readonly ILogger<Projectile> _logger = null!;
[Inject] private readonly ITargetSpawner _targetSpawner = null!; [Inject] private readonly IValueGetter<ITargetSpawner> _targetSpawner = null!;
// Called when the node enters the scene tree for the first time. // Called when the node enters the scene tree for the first time.
public override void _Ready() public override void _Ready()
{ {
_targetSpawner.TargetSpawned _targetSpawner.Value.TargetSpawned
.Subscribe(_ => _logger.LogInformation("Projectile got informed of target spawning")).AddTo(this); .Subscribe(_ => _logger.LogInformation("Projectile got informed of target spawning")).AddTo(this);
} }
} }
+5 -5
View File
@@ -1,22 +1,24 @@
using R3;
using Godot; using Godot;
using GodotHostTest.GodotDI; using GodotHostTest.GodotDI;
using GodotHostTest.Helpers; using GodotHostTest.Helpers;
using GodotHostTest.Interfaces; using GodotHostTest.Interfaces;
using R3;
namespace GodotHostTest.Game; namespace GodotHostTest.Game;
public partial class Score : Control, IScore public partial class Score : Control, IScore
{ {
[Inject] private readonly IValueGetter<ITargetSpawner> _targetSpawner = null!;
[Export] private AnimationPlayer _animationPlayer = null!; [Export] private AnimationPlayer _animationPlayer = null!;
[Export] private Label _label = null!; [Export] private Label _label = null!;
[Inject] private readonly ITargetSpawner _targetSpawner = null!;
private int _score; private int _score;
int IScore.Score => _score;
public override void _Ready() public override void _Ready()
{ {
_targetSpawner.TargetSpawned.Subscribe(OnTargetSpawned).AddTo(this); _targetSpawner.Value.TargetSpawned.Subscribe(OnTargetSpawned).AddTo(this);
base._Ready(); base._Ready();
} }
@@ -34,6 +36,4 @@ public partial class Score : Control, IScore
{ {
_label.Text = $"Score: {_score}"; _label.Text = $"Score: {_score}";
} }
int IScore.Score => _score;
} }
+19 -19
View File
@@ -7,19 +7,30 @@ namespace GodotHostTest.Game;
public partial class Target : Node2D, ITarget public partial class Target : Node2D, ITarget
{ {
[Export] public double TimeOutDurationInSeconds;
[Export] public required Timer TimeOutTimer;
[Export] public required Sprite2D Image;
[Export] public required Area2D CollisionArea;
private readonly Subject<Unit> _timedOut = new();
private readonly Subject<Unit> _hit = new(); private readonly Subject<Unit> _hit = new();
[Inject] private readonly ITargetCollector _targetCollector = null!; [Inject] private readonly IValueGetter<ITargetCollector> _targetCollector = null!;
private readonly Subject<Unit> _timedOut = new();
[Export] public required Area2D CollisionArea;
[Export] public required Sprite2D Image;
[Export] public double TimeOutDurationInSeconds;
[Export] public required Timer TimeOutTimer;
public Observable<Unit> TimedOut => _timedOut.AsObservable();
public Observable<Unit> Hit => _hit.AsObservable();
public void Enable()
{
Image.Visible = true;
CollisionArea.Monitoring = true;
TimeOutTimer.Start(TimeOutDurationInSeconds);
}
public override void _Ready() public override void _Ready()
{ {
_targetCollector.NewTarget(this); _targetCollector.Value.NewTarget(this);
} }
public override void _ExitTree() public override void _ExitTree()
@@ -28,10 +39,6 @@ public partial class Target : Node2D, ITarget
_hit.Dispose(); _hit.Dispose();
} }
public Observable<Unit> TimedOut => _timedOut.AsObservable();
public Observable<Unit> Hit => _hit.AsObservable();
// todo: hook to collision // todo: hook to collision
private void OnHit() private void OnHit()
{ {
@@ -40,13 +47,6 @@ public partial class Target : Node2D, ITarget
_hit.OnNext(Unit.Default); _hit.OnNext(Unit.Default);
} }
public void Enable()
{
Image.Visible = true;
CollisionArea.Monitoring = true;
TimeOutTimer.Start(TimeOutDurationInSeconds);
}
private void Disable() private void Disable()
{ {
Image.Visible = false; Image.Visible = false;
+6
View File
@@ -15,4 +15,10 @@ public static class BuilderExtensions
.AddScoped<IValueGetter<TValueType>, IValueGetter<TValueType>, TDestinationScope>(Builder.NoDependencies, .AddScoped<IValueGetter<TValueType>, IValueGetter<TValueType>, TDestinationScope>(Builder.NoDependencies,
_ => valueProvider.Getter); _ => valueProvider.Getter);
} }
public static Builder AddValueProvider<TValueType, TScope>(this Builder builder)
where TScope : RootScope
{
return builder.AddValueProvider<TValueType, TScope, TScope>();
}
} }
-8
View File
@@ -12,12 +12,4 @@ public interface ISceneInstantiator
/// <param name="onScopeCreated">An optional callback invoked once the scope has been created, but before instantiating the scene.</param> /// <param name="onScopeCreated">An optional callback invoked once the scope has been created, but before instantiating the scene.</param>
/// <returns>The created node, with its dependencies satisfied.</returns> /// <returns>The created node, with its dependencies satisfied.</returns>
Node Instantiate(PackedScene packedScene, Delegate? onScopeCreated = null); Node Instantiate(PackedScene packedScene, Delegate? onScopeCreated = null);
/// <summary>
/// Instantiate a packed scene, just like <see cref="PackedScene.Instantiate{T}"/>, but also looks for a scope between the top level children and triggers the dependency injection mechanism when found.
/// </summary>
/// <param name="packedScene">The packed scene to instantiate.</param>
/// <param name="onScopeCreated">An optional callback invoked once the scope has been created, but before instantiating the scene.</param>
/// <returns>The created node, with its dependencies satisfied.</returns>
T Instantiate<T>(PackedScene packedScene, Delegate? onScopeCreated = null) where T : Node;
} }
+1 -1
View File
@@ -2,5 +2,5 @@ namespace GodotHostTest.GodotDI;
public interface IValueGetter<out T> public interface IValueGetter<out T>
{ {
public T Get(); public T Value { get; }
} }
+3 -27
View File
@@ -1,6 +1,4 @@
using System; using System;
using System.Linq;
using Godot;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using OwofGames.GodotHost; using OwofGames.GodotHost;
@@ -12,7 +10,7 @@ namespace GodotHostTest.GodotDI;
/// <summary> /// <summary>
/// The base class for a root scope. Implement this class and its abstract methods to kick off the DI system. /// The base class for a root scope. Implement this class and its abstract methods to kick off the DI system.
/// </summary> /// </summary>
public abstract partial class RootServiceSource : ServiceSource, ISceneInstantiator public abstract partial class RootServiceSource : ServiceSource
{ {
private Host? _host; private Host? _host;
@@ -28,28 +26,6 @@ public abstract partial class RootServiceSource : ServiceSource, ISceneInstantia
private ILogger<RootServiceSource> Logger => _logger ??= Host.GetLogger<RootServiceSource>(); 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() public override void _EnterTree()
{ {
// create the host // create the host
@@ -59,12 +35,12 @@ public abstract partial class RootServiceSource : ServiceSource, ISceneInstantia
.Build(); .Build();
// resolve nodes // resolve nodes
ResolveInjectedNodes(Host.ServiceProvider, null); ResolveInjectedNodes(Host.ServiceProvider.GetRequiredService<IProvider>(), null);
} }
private void InnerConfigure(IServiceCollection serviceCollection) private void InnerConfigure(IServiceCollection serviceCollection)
{ {
serviceCollection.AddSingleton<ISceneInstantiator>(this); serviceCollection.AddTransient<ISceneInstantiator, SceneInstantiator>();
ConfigureServices(serviceCollection); ConfigureServices(serviceCollection);
} }
+30
View File
@@ -0,0 +1,30 @@
using System;
using System.Linq;
using Godot;
using Microsoft.Extensions.Logging;
using OwofGames.GodotLume;
namespace GodotHostTest.GodotDI;
internal class SceneInstantiator(IProvider provider) : ISceneInstantiator
{
/// <inheritdoc />
public Node Instantiate(PackedScene packedScene, Delegate? onScopeCreated = null)
{
var node = packedScene.Instantiate();
var scope = node.GetChildren().OfType<ServiceSource>().SingleOrDefault();
if (scope == null)
provider.Get<ILogger<SceneInstantiator>>().LogDebug(
"Instantiated the scene {PackedSceneName} through ISceneInstantiator.Instantiate, but no scope found.",
packedScene.GetName());
else
scope.ResolveInjectedNodes(provider, onScopeCreated);
return node;
}
public T Instantiate<T>(PackedScene packedScene, Delegate? onScopeCreated = null) where T : Node
{
throw new NotImplementedException();
}
}
@@ -0,0 +1,24 @@
using System;
using Godot;
namespace GodotHostTest.GodotDI;
public static class SceneInstantiatorExtensions
{
/// <summary>
/// Instantiate a packed scene, just like <see cref="PackedScene.Instantiate{T}" />, but also looks for a scope between
/// the top level children and triggers the dependency injection mechanism when found.
/// </summary>
/// <param name="sceneInstantiator">The scene instantiator to use.</param>
/// <param name="packedScene">The packed scene to instantiate.</param>
/// <param name="onScopeCreated">
/// An optional callback invoked once the scope has been created, but before instantiating the
/// scene.
/// </param>
/// <returns>The created node, with its dependencies satisfied.</returns>
private static T Instantiate<T>(this ISceneInstantiator sceneInstantiator, PackedScene packedScene,
Delegate? onScopeCreated = null) where T : Node
{
return (T)sceneInstantiator.Instantiate(packedScene, onScopeCreated);
}
}
+16 -13
View File
@@ -2,7 +2,6 @@ using System;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using Godot; using Godot;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using OwofGames.GodotLume; using OwofGames.GodotLume;
@@ -15,29 +14,28 @@ public partial class ServiceSource : Node
[Export] private string _serviceScope = RootScopeQualifiedName; [Export] private string _serviceScope = RootScopeQualifiedName;
[Export] protected Node?[] InjectedNodes = []; [Export] protected Node?[] InjectedNodes = [];
internal void ResolveInjectedNodes(IServiceProvider serviceProvider, Delegate? onScopeCreated) internal void ResolveInjectedNodes(IProvider provider, Delegate? onScopeCreated)
{ {
var logger = serviceProvider.GetRequiredService<ILogger<ServiceSource>>(); var logger = provider.Get<ILogger<ServiceSource>>();
// if this service source must also act as a scope, create the scope and use its service provider // if this service source must also act as a scope, create the scope and use its service provider
if (_serviceScope != RootScopeQualifiedName) if (_serviceScope != RootScopeQualifiedName)
{ {
// create the scoped provider // create the scoped provider
var serviceScope = ScopeTypesAndNames.GetType(_serviceScope); var serviceScope = ScopeTypesAndNames.GetType(_serviceScope);
var scopedProvider = serviceProvider provider = provider.GetScopedProvider(serviceScope);
.GetRequiredService<IProvider>()
.GetScopedProvider(serviceScope);
// convert it also to an IServiceProvider
var serviceProviderCreator = serviceProvider.GetRequiredService<Func<IProvider, IServiceProvider>>();
serviceProvider = serviceProviderCreator(scopedProvider);
// invoke onScopeCreated, if present // invoke onScopeCreated, if present
// TODO: replace with a source code generation by turning this method private partial with Action<IProvider> argument, and every invocation site calls the necessary provider.Get<...> to build the argument list // TODO: replace with a source code generation by turning this method private partial with Action<IProvider> argument, and every invocation site calls the necessary provider.Get<...> to build the argument list
if (onScopeCreated != null) if (onScopeCreated != null)
{ {
var parameters = onScopeCreated.Method.GetParameters() var parameters = onScopeCreated.Method
.Select(parameterInfo => scopedProvider.Get(parameterInfo.ParameterType)); .GetParameters()
.Select(parameterInfo => provider.Get(parameterInfo.ParameterType))
.ToArray();
onScopeCreated.DynamicInvoke(parameters); onScopeCreated.DynamicInvoke(parameters);
} }
OnScopeCreated(provider);
} }
else if (onScopeCreated != null) else if (onScopeCreated != null)
{ {
@@ -56,7 +54,7 @@ public partial class ServiceSource : Node
{ {
if (field.GetCustomAttribute<InjectAttribute>() == null) continue; if (field.GetCustomAttribute<InjectAttribute>() == null) continue;
var fieldType = field.FieldType; var fieldType = field.FieldType;
var service = serviceProvider.GetRequiredService(fieldType); var service = provider.Get(fieldType);
field.SetValue(node, service); field.SetValue(node, service);
} }
@@ -70,7 +68,7 @@ public partial class ServiceSource : Node
foreach (var parameter in parameters) foreach (var parameter in parameters)
{ {
var parameterType = parameter.ParameterType; var parameterType = parameter.ParameterType;
var service = serviceProvider.GetRequiredService(parameterType); var service = provider.Get(parameterType);
values[i++] = service; values[i++] = service;
} }
@@ -78,4 +76,9 @@ public partial class ServiceSource : Node
} }
} }
} }
// TODO: also add source generator to mark methods in derived classes with [OnScopeCreated] and perform parameter injection
protected virtual void OnScopeCreated(IProvider serviceProvider)
{
}
} }
+1 -4
View File
@@ -38,9 +38,6 @@ public class ValueProvider<T>
private class GetterImplementation(T value) : IValueGetter<T> private class GetterImplementation(T value) : IValueGetter<T>
{ {
public T Get() public T Value => value;
{
return value;
}
} }
} }
+2
View File
@@ -4,6 +4,8 @@
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=_002Fhome_002Fredglow_002Fsources_002FOwofGames_002EGodot_002FOwofGames_002EGodotLume_002EMicrosoft_002EDependencyInjection_002Fbin_002FDebug_002Fnet8_002E0_002FOwofGames_002EGodotLume_002EMicrosoft_002EDependencyInjection_002Edll/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/AddReferences/RecentPaths/=_002Fhome_002Fredglow_002Fsources_002FOwofGames_002EGodot_002FOwofGames_002EGodotLume_002EMicrosoft_002EDependencyInjection_002Fbin_002FDebug_002Fnet8_002E0_002FOwofGames_002EGodotLume_002EMicrosoft_002EDependencyInjection_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=_002Fhome_002Fredglow_002Fsources_002FOwofGames_002EGodot_002FOwofGames_002EGodotLume_002Fbin_002FDebug_002Fnet8_002E0_002FOwofGames_002EGodotLume_002Edll/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/AddReferences/RecentPaths/=_002Fhome_002Fredglow_002Fsources_002FOwofGames_002EGodot_002FOwofGames_002EGodotLume_002Fbin_002FDebug_002Fnet8_002E0_002FOwofGames_002EGodotLume_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AEnumerable_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F71c28e8d0d254cb69b7b78690e099f6183800_003Fa8_003F2e82b19d_003FEnumerable_002Ecs/@EntryIndexedValue">ForceIncluded</s:String> <s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AEnumerable_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F71c28e8d0d254cb69b7b78690e099f6183800_003Fa8_003F2e82b19d_003FEnumerable_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ARuntimeType_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F6cc9b871557b441baa469ce23b255f41dbb200_003F5e_003F88e82907_003FRuntimeType_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelpers_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F6cc9b871557b441baa469ce23b255f41dbb200_003F8e_003Fc3f51c26_003FThrowHelpers_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F6cc9b871557b441baa469ce23b255f41dbb200_003F71_003F4ef26ee8_003FThrowHelper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String> <s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F6cc9b871557b441baa469ce23b255f41dbb200_003F71_003F4ef26ee8_003FThrowHelper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F71c28e8d0d254cb69b7b78690e099f6183800_003F72_003F2da75270_003FThrowHelper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String> <s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F71c28e8d0d254cb69b7b78690e099f6183800_003F72_003F2da75270_003FThrowHelper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/Environment/Hierarchy/Build/BuildTool/DotNetCliExePath/@EntryValue">/usr/lib/dotnet/dotnet</s:String> <s:String x:Key="/Default/Environment/Hierarchy/Build/BuildTool/DotNetCliExePath/@EntryValue">/usr/lib/dotnet/dotnet</s:String>