2

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.

4

1 に答える 1

4

MSDN によると ( http://msdn.microsoft.com/en-US/library/system.codedom.compiler.compilerresults.compiledassembly.aspx )

CompiledAssembly プロパティの get アクセサーは、Load メソッドを呼び出して、コンパイル済みアセンブリを現在のアプリケーション ドメインに読み込みます。

Activator の代わりにAssembly.CreateInstance( http://msdn.microsoft.com/en-US/library/dex1ss7c.aspx ) メソッドを使用できます。タイプ名だけでインスタンスを作成する必要がある場合は、CompilerResults.CompiledAssembly プロパティの値を取得する必要があります。

于 2013-03-17T12:01:40.517 に答える