Search code examples
c#.netdependency-injectioninstantiationactivator

Is it possible to call Activator.CreateInstance on a type in an assembly that is not statically referenced?


Is is possible to user Activator.CreateInstance() to instantiate a type given the Type.FullName and Assembly Name even though the assembly is not referenced by the executing assembly?


Solution

  • Yes, first you have to load the assembly.

    Suppose you have a "plugins" folder to look into:

                foreach (FileInfo f in new DirectoryInfo("c:\\plugins").GetFiles("*.dll"))
                {
                    System.Reflection.Assembly.LoadFrom(f.FullName);
                }
    

    Now assemblies are loaded and you can create the type using Activator.CreateInstance.