I'm talking about c# 3.5 3.0.
I know how to do it when cache or ServiceProvider can have only one instance for the whole application. In this case ServiceProvider can look like this
public static class Service<T>
{
public static T Value {get; set;}
}
and can be used for different types like this:
Service<IDbConnection>.Value = new SqlConnection("...");
Service<IDesigner>.Value = ...;
//...
IDbCommand cmd = Service<IDbConnection>.Value.CreateCommand();
Static cache is also easy:
public static class Cache<T>
{
private static Dictionary<int, T> cache = new Dictionary<int, T>();
public static void Add(int key, T value)
{
cache.Add(key, value);
}
public static T Find(int key)
{
return cache[key];
}
}
and can be used like this:
Cache<string>.Add(1, "test");
Cache<DateTime>.Add(2, DateTime.Now);
//...
string found = Cache<string>.Find(1);
My question is: how can I create similiar cache or service provider when I want to have 2 or more different instances of each. Here is example code, how I want to use service provider:
ServiceProvider provider = new ServiceProvider();
provider.Add<IDbConnection>(new SqlConnection("..."));
provider.Add<IDesigner>(...);
//...
ServiceProvider provider1 = new ServiceProvider();
provider1.Add<IDbConnection>(new SqlConnection("..."));
//...
//...
IDbCommand cmd1 = provider.GetService<IDbConnection>().CreateCommand();
IDbCommand cmd2 = provider1.GetService<IDbConnection>().CreateCommand();
The only implementation that I have in my head is using casting which I want to avoid.
public class ServiceProvider
{
private Dictionary<Type, object> services = new Dictionary<Type, object>();
public void Add<T>(T value)
{
services.Add(typeof(T), value);
}
public T GetService<T>()
{
return (T) services[typeof (T)];
}
}