1

I am creating a WPF app using Ninject. I created my bindings in Application.xaml.vb and then store the kernal in Application.Current.Properties so I'll have those bindings to resolve as needed.

I am getting this error at design time: Cannot create an instance of "MainUserViewModel". If I remove the code out of my MainUserViewModel's constructor, I don't get the error.

Public Sub New()
    'IoC is the kernel
    Dim repository = IoC.Get(Of IUserRepository)()
    _users = New ObservableCollection(Of User)(repository.GetAll()) 
End Sub

However, when I run the code, my the error goes away and my view populates just fine from _users. I would think if there's an error, the code wouldn't compile and (appear to) work.

I've removed every other piece of my VM and added them all back in. The error only appears when I use that line of code.

Can anyone explain why this is happening? I've checked the repository and all of the expected data is there.

EDIT

Is it possible that the error is occurring in the XAML due to the dependencies not being able to be resolved since it wasn't running? So, as far as it knows, that observable is never being initialized?

Yatrix
  • 13,361
  • 16
  • 48
  • 78

1 Answers1

1

Probably the bindings for IoC are not initialized at design time and IoC.Get(Of IUserRepository)() is throwing NinjectActivationException thus the viewmodel cannot be created by designer.

I would move the init code from constructor e.g. to some lazy loaded property.

// sorry for C#
private ObservableCollection<User> _users;
public ObservableCollection<User>
{
     get
     {
          if(_users == null){
              repository = IoC.Get<IUserRepository>();
              _users = new ObservableCollection<User>(repository.GetAll());
          }
          return _users;
     }
}

However, it is not a good idea to wire up all your code with hard coded dependency on IOC container - it is commonly called "service locator anti-pattern". Give a try to approach in this link: Ninject constructor injection in WPF => there is also use of service locator, which will be responsible for creating your ViewModels, but the dependency on IoC is elegantly hidden in one place - composition root.

Community
  • 1
  • 1
mipe34
  • 5,596
  • 3
  • 26
  • 38