private static WeakReference LoadAndExecute(byte[] compiledAssembly, string[] args)
        {
            using (var asm = new MemoryStream(compiledAssembly))
            {
                var assemblyLoadContext = new SimpleUnloadableAssemblyLoadContext();
                var assembly            = assemblyLoadContext.LoadFromStream(asm);

                var entry = assembly.EntryPoint;

                _ = entry != null && entry.GetParameters().Length > 0
                    ? entry.Invoke(null, new object[] { args })
                    : entry.Invoke(null, null);

                assemblyLoadContext.Unload();

                return(new WeakReference(assemblyLoadContext));
            }
        }
Ejemplo n.º 2
0
        public TWrapper Compile <TWrapper>(string code, string typeFullName) where TWrapper : CodeDomTypeWrapper
        {
            var        sourceLanguage = new CSharpLanguage();
            SyntaxTree syntaxTree     = sourceLanguage.ParseText(code, SourceCodeKind.Regular);

            var @interface = typeof(TWrapper).GetInterfaces()[0];
            var reference  = MetadataReference.CreateFromFile(@interface.Assembly.Location);

            var assemblyName = typeof(List <>).GetTypeInfo().Assembly.Location;
            var systemCollectionReference =
                MetadataReference.CreateFromFile(typeof(List <>).GetTypeInfo().Assembly.Location);

            var systemCollectionReference2 = MetadataReference.CreateFromFile(Assembly.Load("System.Collections, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").Location);


            Compilation compilation = sourceLanguage
                                      .CreateLibraryCompilation(assemblyName: "InMemoryAssembly", enableOptimisations: false)
                                      .AddReferences(new List <MetadataReference>()
            {
                reference, systemCollectionReference2
            })
                                      .AddSyntaxTrees(syntaxTree);

            var lst = new List <string>();

            var stream     = new MemoryStream();
            var emitResult = compilation.Emit(stream);


            if (emitResult.Success)
            {
                stream.Seek(0, SeekOrigin.Begin);

                var assemblyLoadContext = new SimpleUnloadableAssemblyLoadContext();
                var assembly            = assemblyLoadContext.LoadFromStream(stream);

                var wrappedType    = assembly.GetType(typeFullName);
                var obj            = Activator.CreateInstance(wrappedType);
                var codeDomWrapper = (TWrapper)Activator.CreateInstance(typeof(TWrapper), new object[] { wrappedType });
                return(codeDomWrapper);
            }

            return(null);
        }