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
+6
View File
@@ -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>();
}
}
-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>
/// <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;
}
+1 -1
View File
@@ -2,5 +2,5 @@ namespace GodotHostTest.GodotDI;
public interface IValueGetter<out T>
{
public T Get();
public T Value { get; }
}
+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);
}
+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.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)
{
}
}
+1 -4
View File
@@ -38,9 +38,6 @@ public class ValueProvider<T>
private class GetterImplementation(T value) : IValueGetter<T>
{
public T Get()
{
return value;
}
public T Value => value;
}
}