base structure

This commit is contained in:
redglow
2026-07-17 09:59:07 +02:00
parent e560a743fb
commit 96fffb2f9e
25 changed files with 466 additions and 55 deletions
+79
View File
@@ -0,0 +1,79 @@
using System;
using System.Linq;
using Godot;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OwofGames.GodotHost;
using OwofGames.GodotLume.Microsoft.DependencyInjection;
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
{
private Host? _host;
private Host Host
{
get => _host ??
throw new InvalidOperationException(
"Some method of RootScope has been invoked before it entered the tree");
set => _host = value;
}
private ILogger<RootServiceSource>? _logger;
private ILogger<RootServiceSource> Logger => _logger ??= Host.GetLogger<RootServiceSource>();
public override void _EnterTree()
{
// create the host
Host = new HostBuilder()
.SetServiceCollectionBuilder(InnerConfigure)
.SetServiceProviderFactory(new LumeServiceProviderFactory())
.Build();
// resolve nodes
ResolveInjectedNodes(Host.ServiceProvider);
}
private void InnerConfigure(IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<ISceneInstantiator>(this);
Configure(serviceCollection);
}
/// <summary>
/// Configure the service collection by adding the registrations your game needs.
/// </summary>
/// <param name="serviceCollection">The service collection to enrich.</param>
protected abstract void Configure(IServiceCollection serviceCollection);
/// <inheritdoc/>
public Node Instantiate(PackedScene packedScene)
{
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);
}
return node;
}
/// <inheritdoc/>
public T Instantiate<T>(PackedScene packedScene)
where T : Node
{
return (T)Instantiate(packedScene);
}
}