WEAVE 06.09 – Softwarearchitektur

Flexible User Interfaces

Damit Anwendungen einfach und flexibel angepasst werden können, müssen sie von vorneherein logisch aufgebaut sein. Das spart nicht nur Zeit und Geld sondern auch Nerven. Wie man ganz einfach ein Desktop-User-Interface gegen ein Web-UI austauscht, erklärt Golo Roden in WEAVE 06.2009

Das endgültige Resultat:

using System;
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Xml.Linq;
  4.  
  5. namespace Microkernel
  6. {
  7.     ///
  8.     /// Represents a service locator.
  9.     ///
  10.     public static class ServiceLocator
  11.     {
  12.         ///
  13.         /// Contains the mappings from contracts to types.
  14.         ///
  15.         private static Dictionary _mappings;
  16.  
  17.         ///
  18.         /// Initializes the  type.
  19.         ///
  20.         static ServiceLocator()
  21.         {
  22.             // Load the configuration.
  23.             _mappings =
  24.                 (from mapping in
  25.                     XElement.Load("ServiceLocator.xml").Element("mappings").Elements("mapping")
  26.                 select
  27.                     new KeyValuePair(
  28.                         Type.GetType(mapping.Attribute("contract").Value),
  29.                         Type.GetType(mapping.Attribute("type").Value))).ToDictionary(
  30.                     kvp => kvp.Key, kvp => kvp.Value);
  31.         }
  32.  
  33.         ///
  34.         /// Gets an instance for the specified contract.
  35.         ///
  36.         /// The type of the contract.
  37.         /// An instance that matches the specified contract.
  38.         public static TContract GetService() where TContract : class
  39.         {
  40.             // Instantiate the type and return it to the caller.
  41.             return (TContract)Activator.CreateInstance(_mappings[typeof(TContract)]);
  42.         }
  43.     }
  44. }

Die Konfigurationsdatei, damit der Mikrokernel weiß, welche Klasse bei der Anforderung einer Schnittstelle instanziiert werden soll.

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <serviceLocator>
  3.  <mappings>
  4.   <mapping contract="" type="" />
  5.  </mappings>
  6. </serviceLocator>