IsRegistered design concern

Mar 3, 2011 at 10:10 AM

IsRegistered forces construction of Registrations list each time. I have quite big application with moderate count of services and I do not register all ViewModels/Views in container (resolving them without registration). It still turns out that when Registrations property is accessed it has some 450+ registrations in it. I wouldn't call current implementation of Registrations a property as it builds list of registrations on every call to its getter. Now the registrations list itself if constructed like this:

- parent container's registrations are put in dictionary.

- container's own registrations are added to this dictionary.

- resulting dictionary is converted into list of ContainerRegistration instances. 

From IsRegistered POV accessing Registrations property with such implementation is plain inefficient. As IsRegistered is the only actual place where Registrations property is used, maybe it would be better to make IsRegistered a first class resident of UnityContainer and back it up with search technique based on direct access to registeredNames field or even going further and adding Contains(Type, string) to NamedTypesRegistry that will check for registration with given (type, name) with fall-back to parent registry if nothing's found.

Mar 3, 2011 at 11:42 AM

So I modified source this way:

- in NamedTypesRegistry I've added method:

public bool ContainsKey(Type t, string name)
{
	List<string> keys;
	if (registeredKeys.TryGetValue(t, out keys))
	{
		if (keys.Contains(name))
			return true;
	}
	if (parent != null)
		return parent.ContainsKey(t, name);
	return false;
}

- moved bool IsRegistered(this IUnityContainer container, Type typeToCheck, string nameToCheck) from UnityContainerExtensions to IUnityContainer with obvious change and backed it up with following implementation:

public bool IsRegistered(Type typeToCheck, string nameToCheck)
{
	Guard.ArgumentNotNull(typeToCheck, "typeToCheck");
	return registeredNames.ContainsKey(typeToCheck, nameToCheck);
}

So container just asks its own registry to lookup for certain (type, name) pair and registry itself handles fall-back to parent's registry scenario by itself. Hope it helps to make Unity better :)