Erwin Van Der Valk has written an extension that allows one to test if a type is registered with Unity. The UnityContainerExtension, called QueryableContainerExtension, hooks into the Registering Event of the Context Class that fires each time a type is registered with the container. Here is his code:
public class QueryableContainerExtension : UnityContainerExtension
{
public List<RegisterEventArgs> Registrations
= new List<RegisterEventArgs>();
protected override void Initialize()
{
Context.Registering += Context_Registering;
}
void Context_Registering(object sender, RegisterEventArgs e)
{
Registrations.Add(e);
}
public bool IsTypeRegistered<TFrom, TTo>()
{
return Registrations.FirstOrDefault((e) => e.TypeFrom ==
typeof(TFrom) && e.TypeTo == typeof(TTo)) != null;
}
public bool IsTypeRegisteredAsSingleton<TFrom, TTo>()
{
return Registrations.FirstOrDefault(
(e) => e.TypeFrom == typeof(TFrom)
&& e.TypeTo == typeof(TTo)
&& typeof(ContainerControlledLifetimeManager)
.IsInstanceOfType(e.LifetimeManager)) != null;
}
}
Per Erwin, you can access it this way:
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
var extension = new QueryableContainerExtension();
container.AddExtension(extension);
container.RegisterType<IDatabase,Database>();
Debug.Assert(extension.
IsTypeRegistered<IDatabase, Database>());
}
}
Actually, Erwin shows it in a Unit Test and I just tossed the code in a console application and used it as above. Sadly, this doesn't help us much within our applications to test if a type exists in the Unity Container, but it would be pretty easy to extend.
Still makes me wonder why this sort of capability is not on the container in the first place.
Check out Erwin's code here.
More Unity Tutorials and Unity Screencasts.