Better use of generics allows Remoting Services

Topics: CAB & Smart Client Software Factory
Oct 11, 2006 at 7:56 AM
originally posted by: PauloMorgado

To allow the use of Remoting (and therefore NMock2), CAB could make better use of generics.

Changing:

public void Add<TService>(TService serviceInstance)
{
Add(typeof(TService), serviceInstance);
}

to:

public void Add<TService>(TService serviceInstance)
{
Guard.ArgumentNotNull(serviceInstance, "serviceInstance");

Build<TService>(serviceInstance);
}

And:

private object Build(Type typeToBuild, Type typeToRegisterAs, object serviceInstance)
{
Guard.TypeIsAssignableFromType(typeToBuild, typeToRegisterAs, "typeToBuild");

if (locator.Contains(new DependencyResolutionLocatorKey(typeToRegisterAs, null), SearchMode.Local))
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.DuplicateService, typeToRegisterAs.FullName));

if (serviceInstance == null)
serviceInstance = BuildFirstTimeItem(typeToBuild, typeToRegisterAs, null);
else if (!container.Contains(serviceInstance))
serviceInstance = BuildFirstTimeItem(typeToBuild, typeToRegisterAs, serviceInstance);
else
BuildRepeatedItem(typeToRegisterAs, serviceInstance);

return serviceInstance;
}

to:


private object Build(Type typeToBuild, Type typeToRegisterAs, object serviceInstance)
{
Guard.TypeIsAssignableFromType(typeToBuild, typeToRegisterAs, "typeToBuild");

return BuildImplementation(typeToBuild, typeToRegisterAs, serviceInstance);
}

private TService Build<TService>(object serviceInstance)
{
Guard.TypeIsCompatibleType<TService>(serviceInstance, "typeToBuild");

return (TService)BuildImplementation(serviceInstance.GetType(), typeof(TService), serviceInstance);
}

private object BuildImplementation(Type typeToBuild, Type typeToRegisterAs, object serviceInstance)
{
if (locator.Contains(new DependencyResolutionLocatorKey(typeToRegisterAs, null), SearchMode.Local))
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.DuplicateService, typeToRegisterAs.FullName));

if (serviceInstance == null)
serviceInstance = BuildFirstTimeItem(typeToBuild, typeToRegisterAs, null);
else if (!container.Contains(serviceInstance))
serviceInstance = BuildFirstTimeItem(typeToBuild, typeToRegisterAs, serviceInstance);
else
BuildRepeatedItem(typeToRegisterAs, serviceInstance);

return serviceInstance;
}

And adding:

public static void TypeIsCompatibleType<T>(object providedInstance, string argumentName)
{
if (!(providedInstance is T))
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
Properties.Resources.TypeNotCompatible, typeof(T), providedInstance.GetType()), argumentName);
}

would validate the that the provided instance is of the T type without failing like it happens with TypeIsAssignableFromType.