A very simple Objects Locator
Sometimes it can be useful to have a static class where you can store instances of classes you use often.
I found this approach useful, especially with MVVM pattern, to set and get ViewModels without using static classes.
The class:
public class MyObjectsLocator
{
private static Dictionary<Type, object> _classesMap = new Dictionary<Type, object>();
public static void Register<TClass>() where TClass : class
{
Type type = typeof(TClass);
//lazy approach
if (!_classesMap.ContainsKey(type))
_classesMap.Add(type, null);
}
public static void Register<TClass>(TClass instance) where TClass : class
{
Type type = typeof(TClass);
if (!_classesMap.ContainsKey(type))
_classesMap.Add(type, instance);
}
public static TClass Resolve<TClass>() where TClass : class
{
try
{
Type type = typeof(TClass);
//lazy approach
if ((TClass)_classesMap[type] == null)
_classesMap[type] = Activator.CreateInstance(type);
return ((TClass)_classesMap[type]);
}
catch { throw new Exception("MyObjectsLocator: Class " + typeof(TClass) + " not registered yet."); }
}
}
Usage:
To set a "lazy" class just Register it with:MyObjectsLocator.Register<MyClass>();
Instead, if you need to register an instanced class:
MyObjectsLocator.Register<MyClass>(myInstance);
Now it will be easy to get the instance with:
var myInstance = MyObjectsLocator.Resolve<MyClass>();
Commenti
Posta un commento