Implementation of IServiceProvider
5
A simple implementation of IServiceProvider for use in plugin style architectures.
using System;
using System.Collections.Generic;
namespace Diametric.Service
{
/// <summary>
/// An implementation of IServiceProvider that uses a dictionary
/// </summary>
public class DictionaryServiceProvider:IServiceProvider
{
private Dictionary<Type, object> services = new Dictionary<Type,object>();
public DictionaryServiceProvider()
{
}
#region IServiceProvider Members
/// <summary>
/// Returns the specified service or null if the service doesn't exist.
/// </summary>
/// <param name="serviceType"></param>
/// <returns></returns>
public object GetService(Type serviceType)
{
object service = null;
services.TryGetValue( serviceType, out service );
return service;
}
#endregion
#region Public API
/// <summary>
/// Adds a service to the service provider's list of services using the object's type as the key.
/// </summary>
/// <param name="service"></param>
public void AddService(object service)
{
services.Add( service.GetType(), service );
}
/// <summary>
/// Adds a service to the service provider's list of services using the provided Type as the key.
/// </summary>
/// <param name="service"></param>
public void AddService(object service, Type key)
{
services.Add( key, service );
}
#endregion
}
}






Good example though, I'll give it +1
For example when you "hide" the main DataStore object and instead provide a "Facade" (not the pattern) that also implements things such as caching or auditing.
In such a scenario The "Facade" object will require the "Internal" service collection (to get access to the DataStore) yet the plugins will be given the "External" service collection (so they can't directly access the DataStore).
A singleton pattern would not permit this object from being created twice (if you're also going to make the Ctor protected/private) and would therefore not allow such valid use of the object in an application.
Thanks for the +1 tho. :D