feat: working version with scopes.
This commit is contained in:
@@ -14,6 +14,8 @@ public partial class GameServiceSource : RootServiceSource
|
||||
builder
|
||||
.AddSingleton<ICurrentLevel, CurrentLevel>()
|
||||
.AddInstance<ILevelDataProvider, LevelsData>(_levelsData)
|
||||
.AddValueProvider<ILevel, RootScope, LevelScope>();
|
||||
.AddValueProvider<ILevel, RootScope, LevelScope>()
|
||||
.AddValueProvider<ITargetCollector, LevelScope>()
|
||||
.AddValueProvider<ITargetSpawner, LevelScope>();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using Godot;
|
||||
using GodotHostTest.GodotDI;
|
||||
using GodotHostTest.Interfaces;
|
||||
using OwofGames.GodotLume;
|
||||
|
||||
namespace GodotHostTest.Game;
|
||||
|
||||
@@ -7,10 +9,9 @@ public partial class LevelServiceSource : ServiceSource
|
||||
{
|
||||
[Export] private TargetSpawner _targetSpawner = null!;
|
||||
|
||||
// protected override void ConfigureServices(IServiceCollection serviceCollection)
|
||||
// {
|
||||
// serviceCollection
|
||||
// .AddSingleton<ITargetCollector>(_targetSpawner)
|
||||
// .AddSingleton<ITargetSpawner>(_targetSpawner);
|
||||
// }
|
||||
protected override void OnScopeCreated(IProvider serviceProvider)
|
||||
{
|
||||
serviceProvider.Get<IValueSetter<ITargetCollector>>().Set(_targetSpawner);
|
||||
serviceProvider.Get<IValueSetter<ITargetSpawner>>().Set(_targetSpawner);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@ public partial class LevelsData : Resource, ILevelDataProvider
|
||||
|
||||
public ILevel GetLevelData(int levelNumber)
|
||||
{
|
||||
var entry = _levelDataEntries[levelNumber];
|
||||
var entry = _levelDataEntries[levelNumber - 1];
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -10,12 +10,12 @@ namespace GodotHostTest.Game;
|
||||
public partial class Projectile : Node2D
|
||||
{
|
||||
[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.
|
||||
public override void _Ready()
|
||||
{
|
||||
_targetSpawner.TargetSpawned
|
||||
_targetSpawner.Value.TargetSpawned
|
||||
.Subscribe(_ => _logger.LogInformation("Projectile got informed of target spawning")).AddTo(this);
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1,22 +1,24 @@
|
||||
using R3;
|
||||
using Godot;
|
||||
using GodotHostTest.GodotDI;
|
||||
using GodotHostTest.Helpers;
|
||||
using GodotHostTest.Interfaces;
|
||||
using R3;
|
||||
|
||||
namespace GodotHostTest.Game;
|
||||
|
||||
public partial class Score : Control, IScore
|
||||
{
|
||||
[Inject] private readonly IValueGetter<ITargetSpawner> _targetSpawner = null!;
|
||||
[Export] private AnimationPlayer _animationPlayer = null!;
|
||||
[Export] private Label _label = null!;
|
||||
[Inject] private readonly ITargetSpawner _targetSpawner = null!;
|
||||
|
||||
private int _score;
|
||||
|
||||
int IScore.Score => _score;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
_targetSpawner.TargetSpawned.Subscribe(OnTargetSpawned).AddTo(this);
|
||||
_targetSpawner.Value.TargetSpawned.Subscribe(OnTargetSpawned).AddTo(this);
|
||||
base._Ready();
|
||||
}
|
||||
|
||||
@@ -34,6 +36,4 @@ public partial class Score : Control, IScore
|
||||
{
|
||||
_label.Text = $"Score: {_score}";
|
||||
}
|
||||
|
||||
int IScore.Score => _score;
|
||||
}
|
||||
+19
-19
@@ -7,19 +7,30 @@ namespace GodotHostTest.Game;
|
||||
|
||||
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();
|
||||
|
||||
[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()
|
||||
{
|
||||
_targetCollector.NewTarget(this);
|
||||
_targetCollector.Value.NewTarget(this);
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
@@ -28,10 +39,6 @@ public partial class Target : Node2D, ITarget
|
||||
_hit.Dispose();
|
||||
}
|
||||
|
||||
public Observable<Unit> TimedOut => _timedOut.AsObservable();
|
||||
|
||||
public Observable<Unit> Hit => _hit.AsObservable();
|
||||
|
||||
// todo: hook to collision
|
||||
private void OnHit()
|
||||
{
|
||||
@@ -40,13 +47,6 @@ public partial class Target : Node2D, ITarget
|
||||
_hit.OnNext(Unit.Default);
|
||||
}
|
||||
|
||||
public void Enable()
|
||||
{
|
||||
Image.Visible = true;
|
||||
CollisionArea.Monitoring = true;
|
||||
TimeOutTimer.Start(TimeOutDurationInSeconds);
|
||||
}
|
||||
|
||||
private void Disable()
|
||||
{
|
||||
Image.Visible = false;
|
||||
|
||||
@@ -15,4 +15,10 @@ public static class BuilderExtensions
|
||||
.AddScoped<IValueGetter<TValueType>, IValueGetter<TValueType>, TDestinationScope>(Builder.NoDependencies,
|
||||
_ => valueProvider.Getter);
|
||||
}
|
||||
|
||||
public static Builder AddValueProvider<TValueType, TScope>(this Builder builder)
|
||||
where TScope : RootScope
|
||||
{
|
||||
return builder.AddValueProvider<TValueType, TScope, TScope>();
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
/// <returns>The created node, with its dependencies satisfied.</returns>
|
||||
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;
|
||||
}
|
||||
@@ -2,5 +2,5 @@ namespace GodotHostTest.GodotDI;
|
||||
|
||||
public interface IValueGetter<out T>
|
||||
{
|
||||
public T Get();
|
||||
public T Value { get; }
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Godot;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OwofGames.GodotLume;
|
||||
|
||||
@@ -15,29 +14,28 @@ public partial class ServiceSource : Node
|
||||
[Export] private string _serviceScope = RootScopeQualifiedName;
|
||||
[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 (_serviceScope != RootScopeQualifiedName)
|
||||
{
|
||||
// create the scoped provider
|
||||
var serviceScope = ScopeTypesAndNames.GetType(_serviceScope);
|
||||
var scopedProvider = serviceProvider
|
||||
.GetRequiredService<IProvider>()
|
||||
.GetScopedProvider(serviceScope);
|
||||
// convert it also to an IServiceProvider
|
||||
var serviceProviderCreator = serviceProvider.GetRequiredService<Func<IProvider, IServiceProvider>>();
|
||||
serviceProvider = serviceProviderCreator(scopedProvider);
|
||||
provider = provider.GetScopedProvider(serviceScope);
|
||||
// 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
|
||||
if (onScopeCreated != null)
|
||||
{
|
||||
var parameters = onScopeCreated.Method.GetParameters()
|
||||
.Select(parameterInfo => scopedProvider.Get(parameterInfo.ParameterType));
|
||||
var parameters = onScopeCreated.Method
|
||||
.GetParameters()
|
||||
.Select(parameterInfo => provider.Get(parameterInfo.ParameterType))
|
||||
.ToArray();
|
||||
onScopeCreated.DynamicInvoke(parameters);
|
||||
}
|
||||
|
||||
OnScopeCreated(provider);
|
||||
}
|
||||
else if (onScopeCreated != null)
|
||||
{
|
||||
@@ -56,7 +54,7 @@ public partial class ServiceSource : Node
|
||||
{
|
||||
if (field.GetCustomAttribute<InjectAttribute>() == null) continue;
|
||||
var fieldType = field.FieldType;
|
||||
var service = serviceProvider.GetRequiredService(fieldType);
|
||||
var service = provider.Get(fieldType);
|
||||
field.SetValue(node, service);
|
||||
}
|
||||
|
||||
@@ -70,7 +68,7 @@ public partial class ServiceSource : Node
|
||||
foreach (var parameter in parameters)
|
||||
{
|
||||
var parameterType = parameter.ParameterType;
|
||||
var service = serviceProvider.GetRequiredService(parameterType);
|
||||
var service = provider.Get(parameterType);
|
||||
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)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -38,9 +38,6 @@ public class ValueProvider<T>
|
||||
|
||||
private class GetterImplementation(T value) : IValueGetter<T>
|
||||
{
|
||||
public T Get()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
public T Value => value;
|
||||
}
|
||||
}
|
||||
@@ -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_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_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_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>
|
||||
|
||||
Reference in New Issue
Block a user