Sunday, June 17, 2012

Dynamic Classes C# (dynamically create objects of all classes that implements an interface)

//How to dynamically create objects of all classes that implements an interface, useful when creating testcases

/*
The method FindAndAddToContainer() below will
(1) find all classes that implements the interface IMyInterface
(2) create a new instance of it
(3) then call the method Add()
*/

   ========================

     bool IsImplementing(Type t, object o)
        {
            if (t.IsAbstract)
            {
                return false;
            }

            Type itype = t.GetInterface(o.ToString());
            return (null != itype);
        }

        public void FindAndAddToContainer()
        {
         
            Assembly assembly = Assembly.GetExecutingAssembly();
            Type[] types = assembly.ManifestModule.FindTypes( IsImplementing,  "IMyInterface");

            foreach (Type t in types)
            {
                 IMyInterface obj = (IMyInterface) Activator.CreateInstance(t);
                Addobj);
            }
        }