Skip to content

Instantly share code, notes, and snippets.

@AmbulantRex
Last active April 28, 2024 21:24
Show Gist options
  • Save AmbulantRex/862c53e87903e5fdd2b2ced10c2b3cbb to your computer and use it in GitHub Desktop.
Save AmbulantRex/862c53e87903e5fdd2b2ced10c2b3cbb to your computer and use it in GitHub Desktop.
Autofac DI in Stride
using System.Linq;
using System.Reflection;
using Autofac;
using Autofac.Core;
using Stride.Engine;
namespace GameApp
{
internal static void Main(string[] args)
{
using (var game = new Game())
{
var builder = new ContainerBuilder();
// Can do anything supported by autofac at this point. This is an example type registration.
// In general, only consider Singleton scopes.
builder.RegisterType<FundsTransferService>().As<IFundsTransferService>();
var container = builder.Build();
foreach (var serviceType in container.ComponentRegistry.Registrations
.SelectMany(x => x.Services)
.OfType<IServiceWithType>()
.Select(x => x.ServiceType))
{
var service = container.Resolve(serviceType);
// Yucky reflection...
MethodInfo method = game.Services.GetType().GetMethod(nameof(game.Services.AddService));
MethodInfo generic = method.MakeGenericMethod(serviceType);
// Add the service to the game services container directly.
// This preserves the references established during DI.
generic.Invoke(game.Services, new object[] { service });
}
game.Run();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment