John Liu .NET

View Original

TIP - Silverlight - InitParams and ApplicationLifeTimeService(s)

I have this love-hate relationship with InitParams

Like

  • Pre-download values to Silverlight, so it's available to the client before Silverlight even starts rendering
  • Don't have to worry about whether Silverlight can talk to any data source - if you can't see the webpage then the problem is elsewhere

Dislike

  • Well it's on the web pageā€¦  anyone could see it, and probably tweak it via DOM manipulation
  • If you bind to this data, you can't really "update" it if the data changes on the server.  If say the user settings has changed, you'll need a F5 refresh to force the Silverlight client to reload.  In a sense this is often treated like read-only data.

One thing we can fix

  • A really large App.Current with lots of different values sucked out from the initParams during App_Start

 

Using ApplicationLifeTimeServices

1. Write a Lifetime Service

    public class CompanyApplicationLifeTimeService : IApplicationService
    {
        static CompanyApplicationLifeTimeService _current = null;

        public static CompanyApplicationLifeTimeService Current
        {
            get
            {
                return _current;
            }
        }

        #region IApplicationService Members

        public void StartService(ApplicationServiceContext context)
        {            
            _current = this;
            var parseThisStuff = context.ApplicationInitParams;
        }

        public void StopService()
        {
            _current = null;
        }

        #endregion
    }

2. Add this to your App.Xaml

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             x:Class="DispatchKing.Silverlight.App"
             xmlns:common="clr-namespace:DispatchKing.Silverlight.Common"
             >
  <Application.ApplicationLifetimeObjects>
    <common:CompanyApplicationLifeTimeService x:Name="CompanyLifeTimeService" />
  </Application.ApplicationLifetimeObjects>
  <Application.Resources>
    <ResourceDictionary>
   ...

 

3. Now anywhere in your code you have access to the service Singleton

CompanyApplicationlifeTimeService.Current.GiveMeStuff