Implementation of IServiceProvider





5
Date Submitted Fri. May. 25th, 2007 8:09 PM
Revision 1 of 1
Beginner Jax
Tags CSharp | IServiceProvider
Comments 2 comments
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
        }
}

 

Simon Potts-Tamman

Comments

Comments Should be a singleton...
Sun. May. 27th, 2007 11:33 AM    Beginner kvj86210
  Comments Good point, although
Mon. May. 28th, 2007 12:57 PM    Beginner Jax

Voting

Votes Down