// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace ICSharpCode.Core.Services
{
///
/// Maintains a list of services that can be shutdown in the reverse order of their initialization.
/// Maintains references to the core service implementations.
///
public abstract class ServiceManager : IServiceProvider
{
volatile static ServiceManager instance = new DefaultServiceManager();
///
/// Gets the static ServiceManager instance.
///
public static ServiceManager Instance {
get { return instance; }
set {
if (value == null)
throw new ArgumentNullException();
instance = value;
}
}
///
/// Gets a service. Returns null if service is not found.
///
public abstract object GetService(Type serviceType);
///
/// Gets a service. Returns null if service is not found.
///
public T GetService() where T : class
{
return GetService(typeof(T)) as T;
}
///
/// Gets a service. Throws an exception if service is not found.
///
public object GetRequiredService(Type serviceType)
{
object service = GetService(serviceType);
if (service == null)
throw new ServiceNotFoundException();
return service;
}
///
/// Gets a service. Throws an exception if service is not found.
///
public T GetRequiredService() where T : class
{
return (T)GetRequiredService(typeof(T));
}
///
/// Gets the logging service.
///
public virtual ILoggingService LoggingService {
get { return (ILoggingService)GetRequiredService(typeof(ILoggingService)); }
}
///
/// Gets the message service.
///
public virtual IMessageService MessageService {
get { return (IMessageService)GetRequiredService(typeof(IMessageService)); }
}
}
sealed class DefaultServiceManager : ServiceManager
{
static ILoggingService loggingService = new TextWriterLoggingService(new DebugTextWriter());
static IMessageService messageService = new TextWriterMessageService(Console.Out);
public override ILoggingService LoggingService {
get { return loggingService; }
}
public override IMessageService MessageService {
get { return messageService; }
}
public override object GetService(Type serviceType)
{
if (serviceType == typeof(ILoggingService))
return loggingService;
else if (serviceType == typeof(IMessageService))
return messageService;
else
return null;
}
}
}