1
votes

I'm using WPF with MVVM Light in my project. I have some small question about SimpleIoC containter and DI. Which is the better way to use it or tell me if I don't need to use DI there.

There is my VM constructor:

public MainViewModel(IDialogService dialogService, IChannelObserverService channelObserverService, IInternalBroadcastService internalBroadcastService, 
                         IUserDataAccessService userDataAccessService, IUserService userService)

And SimpleIoC register:

 SimpleIoc.Default.Register<MainViewModel>(() => {
            return new MainViewModel(SimpleIoc.Default.GetInstance<IDialogService>(),
                                     SimpleIoc.Default.GetInstance<IChannelObserverService>(),
                                     SimpleIoc.Default.GetInstance<IInternalBroadcastService>(),
                                     SimpleIoc.Default.GetInstance<IUserDataAccessService>(),
                                     SimpleIoc.Default.GetInstance<IUserService>()); });

Please tell me, do I need to use DI there? First I had using all services like this:

public MainViewModel(){...}

User user = SimpleIoc.Default.GetInstance<IUserService>().GetCurrentLoggedUser();

or this:

private IDialogService dialogService;

public MainViewModel()
{
    dialogService = = SimpleIoc.Default.GetInstance<IUserService>();
}

private void MyMethod()
{
    dialogService.ShowQuestionDialog(abc,abc,abc);
}

So I didn't use DI when I was creating my View-Models.

1

1 Answers

2
votes

I'd recommend you to use the DI as it enables the development of loosely coupled code. Through DI, you can decrease tight coupling between software components. Also, it makes unit testing convenient.

I would suggest to have constructor like this (as you have mentioned in your post)

public MainViewModel(IDialogService dialogService, IChannelObserverService channelObserverService, IInternalBroadcastService internalBroadcastService, 
                         IUserDataAccessService userDataAccessService, IUserService userService)

But registration can be simplified as

 SimpleIoc.Default.Register<IDialogService, DialogService>();
 //// Other service registrations.

 SimpleIoc.Default.Register<MainViewModel>(); // without injecting the other dependent types. 

With this DI will take to inject the right dependencies while creating an instance of MainViewModel.

So with this above approach, you don't need to Resolve the instance inside your code as it is already inject in constructor, so service code can be simplified as

private void MyMethod()
{
    dialogService.ShowQuestionDialog(abc,abc,abc);
}