Saturday, August 21, 2010

How to load assembly and its references ignoring version number using Reflection

I want to load an assembly A.BC.dll that has a reference to A.XZ.dll and I dont care about the version number for A.BNM.dll, these two assemblies are located in a /ref folder.



using System;
using System.Collections.Generic;
using System.Reflection;
 
namespace MyUtility
{
    public class Utility
    {
        private Type[] GetAllTypes()
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("ref/");
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
 
            Assembly ass1 = Assembly.LoadFrom(path + "\\" + "A.BC.dll");
            Assembly ass2 = Assembly.LoadFrom(path + "\\" + "A.XZ.dll");
 
            Type[] types = ass1.GetTypes();
            return types;
        }
 
        private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            //ignore the vesion number and return any version that has been loaded
            var name = new AssemblyName(args.Name);
            if (name.Name == "A.BC")
            {
                Assembly[] allAss = AppDomain.CurrentDomain.GetAssemblies();
                List<Assembly> list = new List<Assembly>(allAss);
                return list.Find(delegate(Assembly ass)
{ return new AssemblyName(ass.FullName).Name == "A.BC"; });
            }
            return null;
        }
    }
}

When an assembly can not be loaded, AssemblyResolve event will be fired.

Cheers!

1 comments:

lauren said...

Thanks for sharing information. Your blog helped me to load assembly . I spent a lot of time in resolving this issue but found your blog and solved my problem . Thanks.
digital signature software

Post a Comment