/src/NUnit/util/Services/ServiceManager.cs
C# | 103 lines | 79 code | 13 blank | 11 comment | 6 complexity | 1b27276e7f594b49f9245c323aeedfce MD5 | raw file
1// **************************************************************** 2// Copyright 2007, Charlie Poole 3// This is free software licensed under the NUnit license. You may 4// obtain a copy of the license at http://nunit.org 5// **************************************************************** 6 7using System; 8using System.Collections; 9using NUnit.Core; 10 11namespace NUnit.Util 12{ 13 /// <summary> 14 /// Summary description for ServiceManger. 15 /// </summary> 16 public class ServiceManager 17 { 18 private ArrayList services = new ArrayList(); 19 private Hashtable serviceIndex = new Hashtable(); 20 21 private static ServiceManager defaultServiceManager = new ServiceManager(); 22 23 static Logger log = InternalTrace.GetLogger(typeof(ServiceManager)); 24 25 public static ServiceManager Services 26 { 27 get { return defaultServiceManager; } 28 } 29 30 public void AddService( IService service ) 31 { 32 services.Add( service ); 33 log.Debug( "Added " + service.GetType().Name ); 34 } 35 36 public IService GetService( Type serviceType ) 37 { 38 IService theService = (IService)serviceIndex[serviceType]; 39 if ( theService == null ) 40 foreach( IService service in services ) 41 { 42 // TODO: Does this work on Mono? 43 if( serviceType.IsInstanceOfType( service ) ) 44 { 45 serviceIndex[serviceType] = service; 46 theService = service; 47 break; 48 } 49 } 50 51 if ( theService == null ) 52 log.Error( string.Format( "Requested service {0} was not found", serviceType.FullName ) ); 53 else 54 log.Debug( string.Format( "Request for service {0} satisfied by {1}", serviceType.Name, theService.GetType().Name ) ); 55 56 return theService; 57 } 58 59 public void InitializeServices() 60 { 61 foreach( IService service in services ) 62 { 63 log.Info( "Initializing " + service.GetType().Name ); 64 try 65 { 66 service.InitializeService(); 67 } 68 catch (Exception ex) 69 { 70 log.Error("Failed to initialize service", ex); 71 } 72 } 73 } 74 75 public void StopAllServices() 76 { 77 // Stop services in reverse of initialization order 78 // TODO: Deal with dependencies explicitly 79 int index = services.Count; 80 while (--index >= 0) 81 { 82 IService service = services[index] as IService; 83 log.Info( "Stopping " + service.GetType().Name ); 84 try 85 { 86 service.UnloadService(); 87 } 88 catch (Exception ex) 89 { 90 log.Error("Failure stopping service", ex); 91 } 92 } 93 } 94 95 public void ClearServices() 96 { 97 log.Info("Clearing Service list"); 98 services.Clear(); 99 } 100 101 private ServiceManager() { } 102 } 103}