As usual, I’m trying to use a new technology and having problems right off the bat.
I have a Silverlight Business Application + MvvmLight.
In my viewmodel I try to get the logged in users’ roles:
public HomeViewModel()
{
if (IsInDesignMode)
{
// Code runs in Blend --> create design time data.
}
else
{
// Code runs "for real"
DetermineStartableProcesses();
}
}
private void DetermineStartableProcesses()
{
_startableProcesses = new ObservableCollection<WorkflowProcess>(
WebContext.Current.User.Roles.SelectMany(r =>
WorkflowProcess.GetStartableByRole(r))
.Distinct());
}
At runtime, I get this exception:
System.Windows.Markup.XamlParseException occurred
Message=The invocation of the constructor on type 'CompanyHR.ViewModel.ViewModelLocator' that matches the specified binding constraints threw an exception. [Line: 18 Position: 57]
LineNumber=18
LinePosition=57
StackTrace:
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at CompanyHR.App.InitializeComponent()
at CompanyHR.App..ctor()
InnerException: System.ArgumentNullException
Message=Value cannot be null.
Parameter name: source
StackTrace:
at System.Linq.Enumerable.SelectMany[TSource,TResult](IEnumerable`1 source, Func`2 selector)
at CompanyHR.ViewModel.HomeViewModel.DetermineStartableProcesses()
at CompanyHR.ViewModel.HomeViewModel..ctor()
at CompanyHR.ViewModel.ViewModelLocator..ctor()
InnerException:
Looks like the ViewModelLocator is instantiating the ViewModels at app startup before the webcontext get’s created, which means it’s a bad idea for me to do a lot of work in my viewmodel constructors.
So, where at in the viewmodel should I be retrieving data that will get databound?
Instantiate your WebContext in the App constructor. then add it to your resources in the App_startup before you call
I find its easier to do this part in the code behind because of my custom AuthenticationDomainContext and Membershipprovider…But Dereks works well too, i just was using the code behind while i was getting everything working.