lookitskris
lookitskris

Reputation: 678

MVVMlight not adding ViewModels to SimpleIoc in Silverlight 5

I’m building a Silverlight 5 application using MVVM light and I’m attempting to implement Navigation.

In the Silverlight 4 sample that Laurent builds during his Mix 11 talk (which targets SL4) he uses the following code to check if the SimpleIOC container contains an appropriate ViewModel and create one if it doesn’t already exist. The Navigation service is then called using said ViewModel.

if (!SimpleIoc.Default.Contains<NewsItemViewModel>(item.Link.ToString()))
{
    SimpleIoc.Default.Register(
    () => new NewsItemViewModel
    {
       Model = item
                },
       item.Link.ToString());
    }

        _navigationService.NavigateTo(
            new Uri(
                string.Format(ViewModelLocator.NewsItemUrl, item.Link),
                UriKind.Relative)); 

The following code is then executed in the NewsItemView’s OnNavigatedTo method which checks if the NewsItemViewModel exists (which it should, as it was just created) and then pulls it out of the container.

if (DataContext == null)
{
    var url = e.Uri.ToString();
    var itemUrl = url.Substring(url.IndexOf("?") + 1);

    if (!SimpleIoc.Default.Contains<NewsItemViewModel>(itemUrl))
    {
        MessageBox.Show("Item not found");
        return;
    }

    var vm = SimpleIoc.Default.GetInstance<NewsItemViewModel>(itemUrl);
    DataContext = vm;
}

When I attempt to do the same thing in a Silverlight 5 (doing pretty much an exact port of the project) I notice that the SimpleIoc.Default.Contains method does not exist, but a similar ContainsCreated(string key) does exist.

When I attempt to use this new method, the bool check always returns false and as a result the navigation fails (I get the “Item Not Found” message box).

An example of how I have rewritten the offending line is below

if (!SimpleIoc.Default.ContainsCreated<NewsItemViewModel>(itemUrl))

what am I missing here? Any help would be fantastic!

Kris

Upvotes: 0

Views: 600

Answers (1)

SteveL
SteveL

Reputation: 857

How about using

SimpleIoc.Default.IsRegistered<NewsItemViewModel>(itemUrl)

I've been using just GetInstance(key) which creates it if not already created, but it first needs to have been registered, which the above will confirm.

Although you may or may not want to use the key - as that checks for the type and key combination, but I think that as long as

SimpleIoc.Default.IsRegistered<NewsItemViewModel>()

returns true, then you should then be able to use GetInstance with the key

Upvotes: 2

Related Questions