/// <inheritdoc/>
        public IAssemblyLoadContext Create(string name, bool isCollectible = false)
        {
            var ass = new System.Runtime.Loader.AssemblyLoadContext(name, isCollectible);
            var ret = new AssemblyLoadContext(ass);

            return(ret);
        }
Пример #2
0
        public void LoadFile()
        {
            Assembly     currentAssembly      = typeof(AssemblyTests).Assembly;
            const string RuntimeTestsDll      = "System.Reflection.Tests.dll";
            string       fullRuntimeTestsPath = Path.GetFullPath(RuntimeTestsDll);

            var loadedAssembly1 = Assembly.LoadFile(fullRuntimeTestsPath);

            Assert.NotEqual(currentAssembly, loadedAssembly1);

#if netcoreapp
            System.Runtime.Loader.AssemblyLoadContext alc = System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(loadedAssembly1);
            string expectedName = string.Format("Assembly.LoadFile({0})", fullRuntimeTestsPath);
            Assert.Equal(expectedName, alc.Name);
            Assert.Contains(fullRuntimeTestsPath, alc.Name);
            Assert.Contains(expectedName, alc.ToString());
            Assert.Contains("System.Runtime.Loader.IndividualAssemblyLoadContext", alc.ToString());
#endif

            string dir = Path.GetDirectoryName(fullRuntimeTestsPath);
            fullRuntimeTestsPath = Path.Combine(dir, ".", RuntimeTestsDll);

            Assembly loadedAssembly2 = Assembly.LoadFile(fullRuntimeTestsPath);
            Assert.Equal(loadedAssembly1, loadedAssembly2);
        }
        public void CanCreateAndAssignMessageHeaders()
        {
            var message      = new Message <string, string>();
            var messageProxy = message.DuckCast <IMessage>();

            // Call the CachedMessageHeadersHelper using the compile-time assembly
            var headersProxy = CachedMessageHeadersHelper <TopicPartition> .CreateHeaders();

            AssertHeadersProxy(headersProxy);
            messageProxy.Headers = headersProxy;

            // Now use LoadFile to load a second instance and re-run the tests
            var loadFileAssembly     = Assembly.LoadFile(TopicPartitionType.Assembly.Location);
            var loadHeadersDetails   = CreateGenericCreateHeadersMethod(loadFileAssembly);
            var loadFileHeadersProxy = (IHeaders)loadHeadersDetails.CreateHeaders.Invoke(null, null);

            AssertHeadersProxy(loadFileHeadersProxy);
            messageProxy = loadHeadersDetails.Message;

#if NETCOREAPP3_1 || NET5_0
            var alc = new System.Runtime.Loader.AssemblyLoadContext($"NewAssemblyLoadContext");
            var loadContextAssembly = alc.LoadFromAssemblyPath(TopicPartitionType.Assembly.Location);
            var loadContextDetails  = CreateGenericCreateHeadersMethod(loadContextAssembly);

            var loadContextHeadersProxy = (IHeaders)loadContextDetails.CreateHeaders.Invoke(null, null);
            AssertHeadersProxy(loadContextHeadersProxy);
            messageProxy = loadContextDetails.Message;
#endif
        }
Пример #4
0
        /// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
        public FakeAppDomain()
        {
            BaseDirectory = AppContext.BaseDirectory;
#if NETSTANDARD1_5
            _defaultContext = System.Runtime.Loader.AssemblyLoadContext.Default;
#endif
        }
Пример #5
0
        private void OnContextUnloading(System.Runtime.Loader.AssemblyLoadContext context)
        {
            var handler = _contextUnloadingEvent;

            if (handler != null)
            {
                handler.Invoke(context, EventArgs.Empty);
            }
        }
        private static Assembly Resolver(System.Runtime.Loader.AssemblyLoadContext context, AssemblyName assemblyName)
        {
            var asmPath = GetAssemblyPath(assemblyName.Name);

            if (asmPath != null)
            {
                return(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(asmPath));
            }
            return(null);
        }
Пример #7
0
        static Assembly Resolver(System.Runtime.Loader.AssemblyLoadContext context, AssemblyName an)
        {
            var path = GetAssemblyPath(an);

            if (!string.IsNullOrEmpty(path))
            {
                var assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
                return(assembly);
            }
            return(null);
        }
        void UnixSigTermHandler(System.Runtime.Loader.AssemblyLoadContext obj)
        {
            if (SigTermOnce.IsFirstCall())
            {
                // Stop the service
                Con.WriteLine($"The daemon \"{Name}\" received the SIGTERM signal. Shutting down the daemon...");

                InternalStop();

                Con.WriteLine($"The daemon \"{Name}\" completed the SIGTERM handler.");
            }
        }
Пример #9
0
        static System.Reflection.Assembly AssemblyResolvingEventHandler(System.Runtime.Loader.AssemblyLoadContext alc, System.Reflection.AssemblyName name)
        {
            if (name.FullName.StartsWith("System.Resources.ResourceManager.Tests.resources"))
            {
                if (name.FullName.Contains("Culture=af-ZA"))
                {
                    Assert.Equal(System.Runtime.Loader.AssemblyLoadContext.Default, alc);
                    Assert.Equal("System.Resources.ResourceManager.Tests.resources", name.Name);
                    Assert.Equal("af-ZA", name.CultureName);
                    Assert.Equal(0, ResourcesAfAZEvents);
                    ResourcesAfAZEvents++;
                }
            }

            return(null);
        }
Пример #10
0
        /// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
        public FakeAppDomain()
        {
            BaseDirectory = AppContext.BaseDirectory;
#if NETSTANDARD1_5
            _defaultContext = System.Runtime.Loader.AssemblyLoadContext.Default;

            try
            {
                FriendlyName = GetFriendlyNameFromEntryAssembly() ?? GetFriendlyNameFromProcessName() ?? "UnknownAppDomain";
            }
            catch
            {
                FriendlyName = "UnknownAppDomain";
            }
#endif
        }
Пример #11
0
        private Assembly Context_Resolving(System.Runtime.Loader.AssemblyLoadContext obj, AssemblyName assembly)
        {
            var content = obj as CollectibleAssemblyLoadContext;

            if (content != null)
            {
                string dllPath = Path.Combine(AssemblyPath, content.id.ToString(), assembly.Name + ".dll");
                if (!File.Exists(dllPath))
                {
                    throw new FileNotFoundException("未能找到依赖项" + assembly.Name);
                }
                using var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read);
                return(content.LoadFromStream(fs));
            }
            return(null);
        }
Пример #12
0
        public void LoadFromStream_Stream_ShouldMimicSystem()
        {
            var alc = new System.Runtime.Loader.AssemblyLoadContext("any");
            var sut = new AssemblyLoadContext(alc);

            var compiledAssembly = Compile(SourceCode);

            using (var asm = new MemoryStream(compiledAssembly))
            {
                //  Act.
                var res = sut.LoadFromStream(asm);

                //  Assert.
                res.FullName.Should().Be("Any.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
            }
        }
Пример #13
0
        public void AssemblyLoadFromBytes()
        {
            Assembly assembly = typeof(AssemblyTests).Assembly;

            byte[] aBytes = System.IO.File.ReadAllBytes(AssemblyPathHelper.GetAssemblyLocation(assembly));

            Assembly loadedAssembly = Assembly.Load(aBytes);

            Assert.NotNull(loadedAssembly);
            Assert.Equal(assembly.FullName, loadedAssembly.FullName);

            System.Runtime.Loader.AssemblyLoadContext alc = System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(loadedAssembly);
            string expectedName = "Assembly.Load(byte[], ...)";

            Assert.Equal(expectedName, alc.Name);
            Assert.Contains(expectedName, alc.ToString());
            Assert.Contains("System.Runtime.Loader.IndividualAssemblyLoadContext", alc.ToString());
        }
Пример #14
0
        public static async Task Main(string[] args)
        {
            using var listener = StartHttpListenerWithPortResilience(out var uri);

            await RunAsync(typeof(HttpClient), uri);

            for (int i = 0; i < 5; i++)
            {
                var assembly = Assembly.LoadFile(typeof(HttpClient).Assembly.Location);
                await RunAsync(assembly.GetType("System.Net.Http.HttpClient"), uri);
            }

#if NETCOREAPP3_1 || NET5_0
            for (int i = 0; i < 5; i++)
            {
                var alc      = new System.Runtime.Loader.AssemblyLoadContext($"Context: {i}");
                var assembly = alc.LoadFromAssemblyPath(typeof(HttpClient).Assembly.Location);
                await RunAsync(assembly.GetType("System.Net.Http.HttpClient"), uri);
            }
#endif
        }
Пример #15
0
        static void Main(string[] args)
        {
            string prefix = "";

            if (args.Length > 0)
            {
                prefix = args[0];
            }

            // Use the compile-time types and run the tests
            using (var redisManager = new PooledRedisClientManager(Host()))
                using (var redis = (RedisClient)redisManager.GetClient())
                {
                    RunServiceStack(prefix, new RedisClientWrapper(redis));
                }

            // Now use LoadFile to load a second instance and re-run the tests
            var loadFileAssembly = Assembly.LoadFile(_clientManagerType.Assembly.Location);

            using (IDisposable redisManager = (IDisposable)InstantiateClientManagerFromAssembly(loadFileAssembly))
                using (IDisposable redis = (IDisposable)GetClientFromClientManager(redisManager))
                {
                    RunServiceStack(prefix, new RedisClientWrapper(redis));
                }

#if NETCOREAPP3_1 || NET5_0
            var alc         = new System.Runtime.Loader.AssemblyLoadContext($"NewAssemblyLoadContext");
            var alcAssembly = alc.LoadFromAssemblyPath(typeof(PooledRedisClientManager).Assembly.Location);

            using (IDisposable redisManager = (IDisposable)InstantiateClientManagerFromAssembly(alcAssembly))
                using (IDisposable redis = (IDisposable)GetClientFromClientManager(redisManager))
                {
                    RunServiceStack(prefix, new RedisClientWrapper(redis));
                }
#endif
        }
Пример #16
0
 private static void B_Unloading(System.Runtime.Loader.AssemblyLoadContext obj)
 {
     Console.WriteLine("B Unloding!");
 }
Пример #17
0
 Assembly?AssemblyLoadContext_Resolving(System.Runtime.Loader.AssemblyLoadContext context, AssemblyName name) => ResolveAssembly(name.Name);
Пример #18
0
 private static void Unload(System.Runtime.Loader.AssemblyLoadContext obj)
 {
 }
Пример #19
0
 private void App_Unloading(System.Runtime.Loader.AssemblyLoadContext obj)
 {
     Trace.WriteLine($"INF Unloading {obj.Name}");
 }
Пример #20
0
 private void Default_Unloading(System.Runtime.Loader.AssemblyLoadContext obj)
 {
     _cancellationToken.Cancel();
     System.Runtime.Loader.AssemblyLoadContext.Default.Unloading -= Default_Unloading;
 }
Пример #21
0
 /// <inheritdoc />
 public AssemblyLoadContext(System.Runtime.Loader.AssemblyLoadContext assemblyLoadContext)
 {
     this.assemblyLoadContext = assemblyLoadContext;
 }
Пример #22
0
        public Type GenerateProxy(Type serviceContract)
        {
            var assemblyName = new AssemblyName(serviceContract.FullName + ".Proxy");

            bool saveAssembly;
            var  assemblyBuilder = CreateAssemblyBuilder(AppDomain.CurrentDomain, assemblyName, out saveAssembly);
            var  moduleBuilder   = CreateModuleBuilder(assemblyBuilder, saveAssembly);
            var  clientType      = CreateClientType(serviceContract, moduleBuilder);

            if (saveAssembly)
            {
#if NET48
                assemblyBuilder.Save(assemblyName.Name + ".dll");
#else
                // Don't take a dedendency on Lokad.ILPack.nupkg. Also, at the time of this writing
                // the most current version (0.6.1) did caused an exception. Building the repo
                // (74f8fe7) and referencing the created DLL did work.
                string directory   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string helper      = Path.Combine(directory, "Lokad.ILPack.dll");
                bool   foundHelper = false;

                if (!File.Exists(helper))
                {
                    helper = Environment.GetEnvironmentVariable("WCFPROXY_SAVE_HELPER");
                    if (!string.IsNullOrEmpty(helper) && File.Exists(helper))
                    {
                        foundHelper = true;
                    }
                }
                else
                {
                    foundHelper = true;
                }

                if (foundHelper)
                {
                    var ldx = new System.Runtime.Loader.AssemblyLoadContext(helper, true);
                    try
                    {
                        var hass      = ldx.LoadFromAssemblyPath(helper);
                        var genType   = hass.GetType("Lokad.ILPack.AssemblyGenerator");
                        var genMethod = genType.GetMethod("GenerateAssembly", new[] { typeof(Assembly), typeof(string) });

                        var    generator  = Activator.CreateInstance(genType);
                        string outputFile = Path.Combine(AssemblyOutputDirectory, assemblyName.Name + ".dll");
                        genMethod.Invoke(generator, new object[] { assemblyBuilder, outputFile });
                    }
                    finally
                    {
                        ldx.Unload();
                    }
                }
                else
                {
                    Trace.WriteLine($"Saving assembly to file is not supported. " +
                                    $"File '{AssemblyOutputDirectory}\\{assemblyName}.dll' not created");
                }
#endif
            }

            return(clientType);
        }
Пример #23
0
 private static void SigTermEventHandler(System.Runtime.Loader.AssemblyLoadContext obj)
 {
 }
Пример #24
0
 private static void Domain_Unloading(System.Runtime.Loader.AssemblyLoadContext obj)
 {
     Console.WriteLine("\t\t触发回收事件!");
 }
Пример #25
0
 /// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
 public FakeAppDomain()
 {
     BaseDirectory   = AppContext.BaseDirectory;
     _defaultContext = System.Runtime.Loader.AssemblyLoadContext.Default;
 }
Пример #26
0
        private Assembly DefaultOnResolving(System.Runtime.Loader.AssemblyLoadContext assemblyLoadContext, AssemblyName assemblyName)
        {
            Assembly assembly;

            return(cachedAssemblies.TryGetValue(assemblyName.FullName, out assembly) ? assembly : null);
        }
 public static void InitializeDefaultContext(System.Runtime.Loader.AssemblyLoadContext context)
 {
 }
Пример #28
0
        private SvgDocument CreateDocument(string userCode)
        {
            var source = $@"using System;
using System.Drawing;
using System.IO;
using Svg;

class Program
{{
    public static SvgDocument CreateDocument()
    {{
        SvgDocument svgDoc = null;
        {userCode}
        return svgDoc;
    }}
}}
";

            var sourcePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly()?.Location ?? string.Empty);
            var sourceText = SourceText.From(source, Encoding.UTF8);

            var options = CSharpParseOptions.Default
                          .WithLanguageVersion(LanguageVersion.CSharp8);

            var syntaxTree = CSharpSyntaxTree.ParseText(
                sourceText,
                options
                )
                             .WithFilePath(Path.Combine(sourcePath, "Program.cs"));

            var runtimeDirectoryPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
            var references           = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(Path.Combine(runtimeDirectoryPath, "mscorlib.dll")),
                MetadataReference.CreateFromFile(Path.Combine(runtimeDirectoryPath, "System.Runtime.dll")),
#if NETFRAMEWORK
                MetadataReference.CreateFromFile(Path.Combine(runtimeDirectoryPath, "System.Drawing.dll")),
                MetadataReference.CreateFromFile(Path.Combine(runtimeDirectoryPath, "System.Xml.dll")),
#else
                MetadataReference.CreateFromFile(Path.Combine(runtimeDirectoryPath, "System.Drawing.Primitives.dll")),
                MetadataReference.CreateFromFile(Path.Combine(runtimeDirectoryPath, "System.Private.Xml.dll")),
                MetadataReference.CreateFromFile(Path.Combine(runtimeDirectoryPath, "System.Xml.ReaderWriter.dll")),
#endif
                MetadataReference.CreateFromFile(Path.Combine(sourcePath, "Svg.dll")),
            };

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                     .WithOptimizationLevel(OptimizationLevel.Release);

            var compilation = CSharpCompilation.Create(
                "ConsoleApp",
                new[] { syntaxTree },
                references,
                compilationOptions);

            using (var stream = new MemoryStream())
            {
                var emitResult = compilation.Emit(stream);
                if (!emitResult.Success)
                {
                    var messages = new StringBuilder();
                    foreach (var diagnostic in emitResult.Diagnostics)
                    {
                        var pos      = diagnostic.Location.GetLineSpan();
                        var location = $"({pos.StartLinePosition.Line + 1 - 10},{pos.StartLinePosition.Character + 1})";
                        messages.AppendLine($"{location}: {diagnostic.Severity} {diagnostic.Id}: {diagnostic.GetMessage()}");
                    }
                    throw new InvalidProgramException(messages.ToString());
                }

#if !NETFRAMEWORK
                var assemblyLoadContext = new System.Runtime.Loader.AssemblyLoadContext(compilation.AssemblyName, true);
#endif
                try
                {
                    stream.Seek(0, SeekOrigin.Begin);
#if NETFRAMEWORK
                    var assembly = System.Reflection.Assembly.Load(stream.ToArray());
#else
                    var assembly = assemblyLoadContext.LoadFromStream(stream);
#endif

                    var type   = assembly.GetType("Program");
                    var method = type?.GetMethod("CreateDocument");
                    return(method?.Invoke(null, null) as SvgDocument);
                }
                catch (Exception ex)
                {
                    throw ex.InnerException ?? ex;
                }
#if !NETFRAMEWORK
                finally
                {
                    assemblyLoadContext.Unload();
                }
#endif
            }
        }