using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace newtelligence.DasBlog.Runtime{
public static class DataServiceFactory<T>
{
static readonly object servicesLock = new object();
static readonly IDictionary<string, T> services = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
public static T GetService(string location, Type defaultType)
{
return GetService(location, defaultType, null);
}
public static T GetService(string location, Type defaultType, params object[] optArgs)
{
if (string.IsNullOrEmpty(location)) { throw new ArgumentNullException("location"); }
T service;
// try to get the service
if (!services.TryGetValue(location, out service))
{
// setup the arguments for the dynamic constructor
// invocation.
object[] args;
if (optArgs == null || optArgs.Length == 0)
{
args = new object[] { location };
}
else
{
args = new object[optArgs.Length + 1];
args[0] = location;
Array.Copy(optArgs, 0, args, 1, optArgs.Length);
}
// find the type to init
var type = StorageConfigManager.GetServiceType(typeof(T)) ?? defaultType;
lock (servicesLock)
{
// did someone beat us?
if (!services.TryGetValue(location, out service))
{
// Create new
service = (T)Activator.CreateInstance(type, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, args, null);
services.Add(location, service);
}
}
}
return service;
}
}
}
|