Resolve a type using Unity without an assembly/project reference

Jul 31, 2009 at 7:29 PM

I am using Unity within an enterprise project and it's working well. I would like to be able to resolve a type though without any explicit project reference. In fact, the assembly in which the concrete type resides would be in a completely different directory and Visual Studio project would have NO reference to the assembly at all.

This could easily be done through Reflection and Assembly.LoadFile(dllPath), but I want to do it using Unity.

How could I accomlish this?

Aug 1, 2009 at 1:56 AM

This is how PRISM  (which relies heavily on Unity) accomplishes it; after proper configuration I placed a breakpoint and stepped through it - amazing stuff to say the least.... 

Excerpt from DirectoryModuleCatalog.cs

 private IEnumerable<ModuleInfo> GetNotAllreadyLoadedModuleInfos(DirectoryInfo directory, Type IModuleType)
{
    Assembly[] alreadyLoadedAssemblies = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies();
    return directory.GetFiles("*.dll")
        .Where(file => alreadyLoadedAssemblies
                           .FirstOrDefault(
                           assembly =>
                           String.Compare(Path.GetFileName(assembly.Location), file.Name,
                                          StringComparison.OrdinalIgnoreCase) == 0) == null)
        .SelectMany(file => Assembly.ReflectionOnlyLoadFrom(file.FullName)
                                .GetExportedTypes()
                                .Where(IModuleType.IsAssignableFrom)
                                .Where(t => t != IModuleType)
                                .Where(t => !t.IsAbstract)
                                .Select(type => CreateModuleInfo(type)));
}