-
I'm trying to use VContainer to inject dependencies into nested objects that are not derived from Suppose I represent my game logic in systems like so: public sealed class PhysicsSystem : IExecuteSystem
{
private readonly IPhysicsService _physics;
private readonly ITimeService _time;
private readonly IPhysicsConfig _physicsConfig;
public PhysicsSystem(IPhysicsService physics, ITimeService time, IPhysicsConfig physicsConfig)
{
// Initialization
}
public void Execute()
{
// Logic goes here
}
} I have dozens of these systems, nearly all of which depend on some common services or configuration objects. To keep my code manageable, I group them in public sealed class GameplayFeature : Feature
{
public GameplayFeature()
{
Add(new PhysicsSystem(/* ... */));
Add(new AiFeature(/* ... */));
}
} Note that the order in which these systems are declared and added is important. The naive thing would be to register every So what would you suggest? My requirements are:
One thing I won't do is to inject the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
I have decided to bite the bullet and just use a big-ass constructor. My My using VContainer;
public sealed class GameplayFeature : Feature
{
public GameplayFeature(
PhysicsSystem physics,
AiFeature ai
)
{
Add(physics);
Add(ai);
}
public static void Register(IContainerBuilder builder)
{
builder.Register<GameplayFeature>(Lifetime.Singleton);
builder.Register<PhysicsSystem>(Lifetime.Singleton);
AiFeature.Register(builder); // Implementation is similar to this one, but with AiFeature's systems and sub-features
}
} (This particular constructor is small, but I have several like it that are larger.) |
Beta Was this translation helpful? Give feedback.
-
Hello. Sorry for the late response. 1. I recently added the feature to set up an instance using a lambda expression. #206So, how about the following statement. builder.Register(container =>
{
var feature = new GamePlayFeature();
feature.Add(container.Resolve<PhysicsSystem>());
feature.Add(contaienr.Resovle<AiFeature>());
return feature;
}, Lifetime.Singleton) In this case, we will be using the IObjectResolver directly, but we can isolate only the settings. ( You may also want to create an extension method to IObjectResolver to make it easier to write the above. 2. Maybe we can Resolve it as a collectionYou can register multiple instances of the same type, and then Resolve the collection. builder.Register<System, PhysicsSystem>(Lifetime.Scoped);
builder.Register<Syste, FooSystem>(Lifetime.Scoped);
// ...
builder.Register<GamePlayFeature>(Lifetime.Singleton); class GamePlayFeature
{
public GamePlayFeature(IReadOnlyList<System> systems)
{
foreach (var system in systems)
{
Add(system);
}
}
} |
Beta Was this translation helpful? Give feedback.
I have decided to bite the bullet and just use a big-ass constructor. My
PhysicsSystem
as defined in the original post is unchanged.My
GameplayFeature
now looks like this: