[MVVM] InstanceResolver

En este post compartiré como implementar de manera muy básica un InstanceResolver para clases con un constructor sin sobrecargas.

InstanceResolver.cs


public class InstanceResolver
{
public static readonly InstanceResolver Default = new InstanceResolver();

private InstanceResolver() { }

private readonly IDictionary<Type, Type> TypeMap = new Dictionary<Type, Type>();
private readonly IDictionary<Type, object> Instances = new Dictionary<Type, object>();

public T Resolve<T>()
{
return (T)Resolve(typeof(T));
}

public void Register<TFrom>()
{
TypeMap.Add(typeof(TFrom), typeof(TFrom));
}

public void Register<TFrom, TTo>()
{
TypeMap.Add(typeof(TFrom), typeof(TTo));
}

private object Resolve(Type type)
{
try
{
object resolvedType = null;

if (Instances.ContainsKey(type))
{
resolvedType = Instances[type];
}
else
{
resolvedType = Activator.CreateInstance(TypeMap[type]);
Instances.Add(type, resolvedType);
}

return resolvedType;
}
catch (Exception)
{
throw new Exception(string.Format("Could not resolve type {0}", type.FullName));
}
}
}

¿Como usar?


public class ViewModelLocator
{
public ViewModelLocator()
{
InstanceResolver.Default.Register<LoginVM>();
InstanceResolver.Default.Register<UsuarioVM>();
}

public LoginVM LoginVM
{
get
{
return InstanceResolver.Default.Resolve<LoginVM>();
}
}

public UsuarioVM UsuarioVM
{
get
{
return InstanceResolver.Default.Resolve<UsuarioVM>();
}
}
}

Agregue un comentario

Su dirección de correo no se hará público. Los campos requeridos están marcados *