Question

How can I Load an assembly to memory and instatiate one of its types by using their name?

I have this to compile:

    /// <summary>
    /// Compiles the input string and saves it in memory
    /// </summary>
    /// <param name="source"></param>
    /// <param name="referencedAssemblies"></param>
    /// <returns></returns>
    public static CompilerResults LoadScriptsToMemory(string source, List<string> referencedAssemblies)
    {
        CompilerParameters parameters = new CompilerParameters();

        parameters.GenerateInMemory = true;
        parameters.GenerateExecutable = false;
        parameters.IncludeDebugInformation = false;

        //Add the required assemblies
        foreach (string reference in referencedAssemblies)
            parameters.ReferencedAssemblies.Add(reference);

        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
        {
            if (asm.Location.Contains("Microsoft.Xna") || asm.Location.Contains("Gibbo.Library") 
                || asm.Location.Contains("System"))
            {
                parameters.ReferencedAssemblies.Add(asm.Location);
            }
        }

        return Compile(parameters, source);
    }

    /// <summary>
    /// Compiles a source file with the given parameters and source
    /// </summary>
    /// <param name="parms"></param>
    /// <param name="source"></param>
    /// <returns></returns>
    private static CompilerResults Compile(CompilerParameters parameters, string source)
    {
        CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
        return compiler.CompileAssemblyFromSource(parameters, source);
    }

Then, I try to use this to instantiate on of the members generated in memory by the code above:

    var handler = Activator.CreateInstance(SceneManager.ScriptsAssembly.FullName, name);
    ObjectComponent oc = (ObjectComponent)handler.Unwrap();

SceneManager.ScriptsAssembly.FullName :> I save the compiled assembly in SceneManager.ScriptsAssembly.

name :> name of the type I want to load

I got this error:

Error loading scene: Could not load file or assembly 'nhvneezw, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

The assembly name is correct. What may it be?

Thanks in advance.

Was it helpful?

Solution

According to MSDN (http://msdn.microsoft.com/en-US/library/system.codedom.compiler.compilerresults.compiledassembly.aspx)

The get accessor for the CompiledAssembly property calls the Load method to load the compiled assembly into the current application domain

You can use Assembly.CreateInstance(http://msdn.microsoft.com/en-US/library/dex1ss7c.aspx) method instead of Activator. If you need to create instance only by type name, you have to get value of CompilerResults.CompiledAssembly property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top