-
-
Save w0wca7a/9aaea0440f53b834dbebf23dd9111e51 to your computer and use it in GitHub Desktop.
Autofac DI in Stride
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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