hadashiA / VContainer

The extra fast, minimum code size, GC-free DI (Dependency Injection) library running on Unity Game Engine.
https://vcontainer.hadashikick.jp
MIT License
1.89k stars 165 forks source link

Factories and entry points #561

Closed Valerio-Corso closed 7 months ago

Valerio-Corso commented 11 months ago

I am testing out the capabilities of VContainer for a little side project, now what I am trying to figure out is the best way to setup a factory, all works fine with instantiating prefabs but it gets a bit more complex if I want to follow an MVP pattern.

Besides manually creating the presenter and its dependencies I found the two solutions below to work. Is there a way to easily register entry points such as ITickable or IStartable for classes created at runtime through a factory? that would be the only piece of logic I am missing, otherwise I am happy with the result.

Note: for the purpose if this example there is no model but it would be easy to add.

builder.RegisterViewFactory<CircleView>(_circlePrefab, Lifetime.Scoped);
builder.RegisterFactory<CircleView, ICirclePresenter>(container =>
{
    return (view) =>
    {
        var presenter = new CirclePresenter();
        container.Inject(presenter);
        presenter.Init(view);
        return presenter;
    };
}, Lifetime.Singleton);
builder.RegisterEntryPoint<CirclePresenter>(Lifetime.Transient);
builder.RegisterFactory<CircleView, ICirclePresenter>(container =>
{
    return (view) =>
    {
        var presenter = container.Resolve<ICirclePresenter>();
        presenter.Init(view);
        return presenter;
    };
}, Lifetime.Singleton);