简体   繁体   中英

Dependency injection for multiple instance without service locator

I'm writing a WPF application using Unity as Ioc for Dependency Injection

I create my main window with:

container.RegisterType<IMainWindow, MainWindow>();
container.RegisterType<ISecondWindow, SecondWindow>();

container.Resolve<IMainWindow>().Show();

All other windows are injected with Dependency injection, for example in my "MainWindow" i can open trough a button my "SecondWindow",so i have ISecondWindow in the MainWindow constructor

public partial class MainWindow: Window, IMainWindow
{
    public MainWindow(IMainWindowViewModel viewModel, ISecondWindow secondWindow)
    {
        //with this solution I can open the second window from IMainWindowViewModel (viewmodels has no reference to windows which are in a separate project)
        viewModel.OpenSecondWindow += (s,e) => secondWindow.Show();
    }

SecondWindow has not other windows so it defines only ViewModels in his constructor

public partial class SecondWindow: Window, ISecondWindow
{
    public SecondWindow(ISecondWindowViewModel viewModel)

all the dependencies are then resolved in cascade (WINDOW -> VIEWMODEL -> SERVICE -> REPOSITORY)

This perfectly works until i have only one instance of my second window, but...

what about if I can have N windows/instance of my ISecondWindow opened at same time (for example I have a list, I double click on first row and an ISecondWindow is open with first row details, then i double click on second row and ANOTHER ISecondWindow is open with second row details (so I can view first and second row details at the same time))?

with DI this can't be accomplished, because I have and can use only one instance of my ISecondWindow.

Only solution which I have in my mind to solving this problem is using Service locator, but Service locator is an anti pattern and i wouldn't use it.

Do you have any ideas/seuggestion to solve this?

Try registering your ISecondWindow using a TransientLifetimeManager.

http://www.tutorialsteacher.com/ioc/lifetime-manager-in-unity-container

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM