0

I am currently working on a Picture Management software where I have to follow pretty strict requirements due to specified interfaces I am not allowed to change. Therefore I am forced to have a List<PictureViewModel> containing ViewModels created from PictureModels, and not one ViewModel, where I would simply switch out the PictureModel reference I keep in the ViewModel.

The part I am struggling with is converting the List<PictureModel> to List<PictureViewModel>, while injecting the IBusinessLayer dependency into the constructor of the PictureViewModel class (public PictureViewModel(PictureModel model, IBusinessLayer bLayer)) and trying not to break any DI patterns.

I am using Ninject as dependency injection framework.

I thought about the following solutions:

1) Creating the following bind inside my configuration NinjectModule, injecting it into the ViewModel containing the List<PictureViewModel>. This Func would act as the converter between Model and ViewModel.

Bind<Func<PictureModel, PictureViewModel>>().ToMethod(context => (model =>
{
    var modelArg = new ConstructorArgument("model", model);
    return context.Kernel.Get<PictureViewModel>(modelArg);
}));

2) Similar to 1: creating a conversion class I would inject into the ViewModel containing the List<PictureViewModel>.

public class PictureModelToPictureViewModelConverter
{
    private readonly IBusinessLayer _businessLayer;

    [Inject]
    public PictureModelToPictureViewModelConverter(IBusinessLayer businessLayer)
    {
        _businessLayer = businessLayer;
    }

    public PictureViewModel Convert(PictureModel mdl)
        => new PictureViewModel(mdl, _businessLayer);
}

3) As the goal is to save edits (through the business layer) made to the pictures metadata, I could try to solve this using events, not a DI based solution.

I hope I did not overlook any simple solution.

  • 1
    Whatever you do, make it dead simple. What you've described in your question sounds like you're trying to make a bad architecture into a good one by adding a lot of additional complexity. That's not going to help anyone. – Robert Harvey Apr 3 '18 at 18:55
  • @RobertHarvey Thanks for your comment, I guess you're right, going the path of simplicity is the right thing here. As I'm still pretty new to DI, I wanted to make sure I don't miss any features, and use it wherever it is applicable, but here it really doesn't seem good to force complicated code in. – mholle Apr 3 '18 at 19:11

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.