title: Silverlight: WebContext is not available exception crashes visual studio
body: <p>I have a prism app using RIA services, and my authentication service is in a separate RIA class library.</p>
  
  <p>The program works fine at runtime. Authentication and all.</p>
  
  <p>I am getting a nasty error at design time, though, which crashes both visual studio and blend. Blend will crash immediately when I open the solution. Visual studio will crash when I close the particular view (page). At least blend gave me a crash log after though. The error has to do with me setting an instance of my viewmodel as the datacontext of the view in xaml rather than setting/injecting one at runtime.</p>
  
  <p>So when setting a viewmodel datacontext at runtime, the viewmodel constructor is called when the view is loaded in the designer. And when the view is closed the destructor is called. That is where I am getting the exception that crashes vs/blend. So here is the exception:</p>
  
  <blockquote>
    <p>System.InvalidOperationException: The current instance of WebContext
    is not available.  You must instantiate a WebContext and add it to
    Application.ApplicationLifetimeObjects within the default App
    constructor.    at
    System.ServiceModel.DomainServices.Client.ApplicationServices.WebContextBase.get_Current()
    at MyClassLibrary.WebContext.get_Current()     at
    MyShellProject.ShellViewModel.Finalize()</p>
  </blockquote>
  
  <p>It's odd because I am instantiating a WebContext in my App constructor. And there are no problems at runtime. Only since I added an instance of my viewmodel as the datacontext I get the crash at runtime.</p>
  
  <p>So in my App.xaml I have:</p>
  
  <pre><code>&lt;Application.ApplicationLifetimeObjects&gt;
          &lt;MyClassLibrary:WebContext&gt;
              &lt;MyClassLibrary:WebContext.Authentication&gt;
                  &lt;ApplicationServices:FormsAuthentication&gt;
                      &lt;ApplicationServices:FormsAuthentication.DomainContext&gt;
                          &lt;MyClassLibrary_Web:MyAuthenticationContext /&gt;
                      &lt;/ApplicationServices:FormsAuthentication.DomainContext&gt;
                  &lt;/ApplicationServices:FormsAuthentication&gt;
              &lt;/MyClassLibrary:WebContext.Authentication&gt;
          &lt;/MyClassLibrary:WebContext&gt;
      &lt;/Application.ApplicationLifetimeObjects&gt;
  </code></pre>
  
  <p>I did also try the code behind equivalent of this in the App constructor. Both have the same result.</p>
  
  <p>This blog post has a little more detail about how my project is set up: <a href="http://avcode.wordpress.com/2010/08/25/authenticaion-prism-wcf-ria-services/" rel="nofollow">http://avcode.wordpress.com/2010/08/25/authenticaion-prism-wcf-ria-services/</a></p>
  
  <p>Anyone have a clue as to why at design time, visual studio is not aware that I have instantiated a WebContext?</p>