jeudi 7 mai 2020

Proper implementation of factory pattern using DI

I've got a question about the cleanest way for constructing new instances of some abstraction in a factory using Dependency Injection. The thing is that I use some presenter which opens it's views multiple times, but when we only "close" some view, it's being disposed, and to open the view again I need to get a new View instance once again and then I can open it.

For now the "factory" looks like this:

class ViewConstructor<TView> :IViewConstructor<TView>
    where TView : class, IView
{
    private readonly IIocContainer _iocContainer;

    public ViewConstructor(IIocContainer iocContainer)
    {
        _iocContainer = iocContainer;
    }

    public TView Construct()
    {
        return _iocContainer.GetInstance<TView>();
    }
}

The thing is, that I know that using IocContainer anywhere but not in the composition root it a bad thing. So I'm guessing if there's some "clean" way to implement this. To sum up, i want to be able to get MULTIPLE instances of the IView from the factory.

Aucun commentaire:

Enregistrer un commentaire