private static Assembly ResolveAssemblyAgain(AssemblyLoadContext sender, AssemblyName assembly) { string assemblyFilename = assembly.Name + ".dll"; s_NumNonNullResolutions++; return sender.LoadFromAssemblyPath(Path.Combine(s_loadFromPath, assemblyFilename)); }
public static void GetAssemblyNameTest_AssemblyNotFound() { Assert.Throws <FileNotFoundException>(() => AssemblyLoadContext.GetAssemblyName("Non.Existing.Assembly.dll")); }
public void UnloadPlugins() { _context.Unload(); _context = CreateContext(); }
private void SqlConnectionFactoryAssemblyLoadContext_Unloading(AssemblyLoadContext obj) { Unload(obj, EventArgs.Empty); }
public abstract Assembly Default_Resolving(AssemblyLoadContext arg1, AssemblyName arg2);
public HostContext(string hostType, string logFile = null) { // Validate args. ArgUtil.NotNullOrEmpty(hostType, nameof(hostType)); _loadContext = AssemblyLoadContext.GetLoadContext(typeof(HostContext).GetTypeInfo().Assembly); _loadContext.Unloading += LoadContext_Unloading; this.SecretMasker.AddValueEncoder(ValueEncoders.JsonStringEscape); this.SecretMasker.AddValueEncoder(ValueEncoders.UriDataEscape); // Create the trace manager. if (string.IsNullOrEmpty(logFile)) { int logPageSize; string logSizeEnv = Environment.GetEnvironmentVariable($"{hostType.ToUpperInvariant()}_LOGSIZE"); if (!string.IsNullOrEmpty(logSizeEnv) || !int.TryParse(logSizeEnv, out logPageSize)) { logPageSize = _defaultLogPageSize; } int logRetentionDays; string logRetentionDaysEnv = Environment.GetEnvironmentVariable($"{hostType.ToUpperInvariant()}_LOGRETENTION"); if (!string.IsNullOrEmpty(logRetentionDaysEnv) || !int.TryParse(logRetentionDaysEnv, out logRetentionDays)) { logRetentionDays = _defaultLogRetentionDays; } // this should give us _diag folder under agent root directory string diagLogDirectory = Path.Combine(new DirectoryInfo(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).Parent.FullName, Constants.Path.DiagDirectory); _traceManager = new TraceManager(new HostTraceListener(diagLogDirectory, hostType, logPageSize, logRetentionDays), this.SecretMasker); } else { _traceManager = new TraceManager(new HostTraceListener(logFile), this.SecretMasker); } _trace = GetTrace(nameof(HostContext)); _vssTrace = GetTrace(nameof(VisualStudio) + nameof(VisualStudio.Services)); // VisualStudioService // Enable Http trace bool enableHttpTrace; if (bool.TryParse(Environment.GetEnvironmentVariable("VSTS_AGENT_HTTPTRACE"), out enableHttpTrace) && enableHttpTrace) { _trace.Warning("*****************************************************************************************"); _trace.Warning("** **"); _trace.Warning("** Http trace is enabled, all your http traffic will be dumped into agent diag log. **"); _trace.Warning("** DO NOT share the log in public place! The trace may contains secrets in plain text. **"); _trace.Warning("** **"); _trace.Warning("*****************************************************************************************"); _httpTrace = GetTrace("HttpTrace"); _diagListenerSubscription = DiagnosticListener.AllListeners.Subscribe(this); } // Enable perf counter trace string perfCounterLocation = Environment.GetEnvironmentVariable("VSTS_AGENT_PERFLOG"); if (!string.IsNullOrEmpty(perfCounterLocation)) { try { Directory.CreateDirectory(perfCounterLocation); _perfFile = Path.Combine(perfCounterLocation, $"{hostType}.perf"); } catch (Exception ex) { _trace.Error(ex); } } }
public Assembly GetAssembly() { ImplementInterface(); CreateConstructor(); string _source = "//------------------------------------------------------------------------------" + Environment.NewLine + "// <auto-generated>" + Environment.NewLine + "// Dynamically created source code. Provisionally created as C# syntax, " + Environment.NewLine + "// because CodeDom is not supported under .NET Core. " + Environment.NewLine + "// </auto-generated>" + Environment.NewLine + "//------------------------------------------------------------------------------" + Environment.NewLine; _source += "namespace " + CodeNameSpace + Environment.NewLine; _source += "{" + Environment.NewLine; _source += " using System;" + Environment.NewLine; _source += " using Stateless;" + Environment.NewLine; _source += " using Stateless.Graph;" + Environment.NewLine; _source += " using LogFSMShared;" + Environment.NewLine; _source += " using System.Linq;" + Environment.NewLine; //_source += " using System.ComponentModel.Primitives;" + Environment.NewLine; _source += " using System.IO;" + Environment.NewLine; _source += " using System.Collections;" + Environment.NewLine; _source += " using System.Collections.Generic;" + Environment.NewLine; _source += " public class " + ClassName + ": LogFSMShared.LogFSMBase, LogFSMShared.ILogFSM " + Environment.NewLine; _source += " {" + Environment.NewLine; _source += " private Dictionary<int,Stateless.StateMachine<State,Trigger>> machines;" + Environment.NewLine; _source += constructorCodeFragment; _source += createProcessEventMethodCodeFragment; _source += createRulesFunctionCodeFragment; _source += createTriggerFunctionCodeFragment; _source += enumDefinitionCodeFragment; _source += triggerDefinitionCodeFragment; _source += " } " + Environment.NewLine; _source += " } " + Environment.NewLine; // export generated cs code for inspection if (parsedCommandLineArguments.Flags.Contains("EXPORT_GENERATED_SOURCE") || parsedCommandLineArguments.IsDebug) { using (StreamWriter sourceWriter = new StreamWriter(sourceFileName)) { sourceWriter.Write(_source); } } Assembly createdAssembly = null; var options = new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, allowUnsafe: false); var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), options: options); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(_source); compilation = compilation.AddSyntaxTrees(syntaxTree); // TODO: Optimize! #region Add Rferences var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); List <MetadataReference> references = new List <MetadataReference>(); references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Private.CoreLib.dll"))); references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Console.dll"))); references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll"))); var usings = compilation.SyntaxTrees.Select(tree => tree.GetRoot().DescendantNodes().OfType <UsingDirectiveSyntax>()).SelectMany(s => s).ToArray(); foreach (var u in usings) { if (File.Exists(Path.Combine(assemblyPath, u.Name.ToString() + ".dll"))) { references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, u.Name.ToString() + ".dll"))); } } references.Add(MetadataReference.CreateFromFile(Path.Combine(parsedCommandLineArguments.RuntimePath, "Stateless.dll"))); references.Add(MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location)); references.Add(MetadataReference.CreateFromFile(Path.Combine(parsedCommandLineArguments.RuntimePath, "LogFSMShared.dll"))); #endregion compilation = compilation.AddReferences(references); //compile using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { CompileErrors.Add(diagnostic.Id + ";" + diagnostic.GetMessage() + ";" + diagnostic.Location); } } else { ms.Seek(0, SeekOrigin.Begin); AssemblyLoadContext context = AssemblyLoadContext.Default; createdAssembly = context.LoadFromStream(ms); } } if (HasErrors) { foreach (string l in CompileErrors) { File.AppendAllText(Path.Combine(parsedCommandLineArguments.OutputPath, "logfsmlasterror.txt"), l); } } return(createdAssembly); }
public SpecFlowV3BaseDiscoverer(AssemblyLoadContext loadContext) { _loadContext = loadContext; }
static void AddUnmanagedLibraryPath(string libPath) => (AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()) as ExtensionLoadContext)? .AddUnmanagedLibraryPath(libPath);
private static Assembly ResolveNullAssembly(AssemblyLoadContext sender, AssemblyName assembly) { return(null); }
internal PluginLoader(PluginConfig config, string baseDir, Type[] sharedTypes) { _mainAssembly = Path.Combine(baseDir, config.MainAssembly.Name + ".dll"); _context = CreateLoadContext(baseDir, config, sharedTypes); }
public static void Load(string libName) { //AppDomain appDomain = AppDomain.CreateDomain("LibDomain_" + Path.GetFileName(libName)); //AssemblyName assemblyName = new AssemblyName(libName); //var core = typeof(object).Assembly; //var corepath = core.CodeBase; //PathAssemblyResolver resolver = new PathAssemblyResolver(new string[] { Path.GetDirectoryName(corepath), $"{Environment.CurrentDirectory}" }); ////MetadataAssemblyResolver resolver = //MetadataLoadContext context = new MetadataLoadContext(resolver, "mscorlib"); //Assembly asm = context.LoadFromAssemblyPath(libName); //var list = asm.CustomAttributes; bool haveMyAttribute = false; using (FileStream fileStream = new FileStream(libName, FileMode.Open, FileAccess.Read, FileShare.Read)) { PEReader peReader = new PEReader(fileStream, PEStreamOptions.LeaveOpen); MetadataReader reader = peReader.GetMetadataReader(); CustomAttributeHandleCollection customAttributes = reader.CustomAttributes; foreach (CustomAttributeHandle item in customAttributes) { try { CustomAttribute attribute = reader.GetCustomAttribute(item); MemberReference ctor = reader.GetMemberReference((MemberReferenceHandle)attribute.Constructor); TypeReference attrType = reader.GetTypeReference((TypeReferenceHandle)ctor.Parent); string nsName = reader.GetString(attrType.Namespace); string typeName = reader.GetString(attrType.Name); Debug.WriteLine($"{nsName}.{typeName}"); if (nsName == "ImageLib.Loader" && typeName == "InitLoaderAttribute") { haveMyAttribute = true; break; } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } peReader.Dispose(); //var asm = Assembly.ReflectionOnlyLoadFrom(libName); //if (asm.CustomAttributes.Any(a => a.AttributeType == typeof(InitLoaderAttribute))) //{ // Assembly assembly = Assembly.LoadFrom(libName); // Load(assembly); //} if (haveMyAttribute) { var context = new AssemblyLoadContext(null, true); fileStream.Position = 0; var asm = context.LoadFromStream(fileStream); Load(asm, null); context.Unloading += a => { }; context.Unload(); } } }
public SpecFlowV31DependencyProvider(AssemblyLoadContext loadContext) { _loadContext = loadContext; }
public SpecFlowV31Discoverer(AssemblyLoadContext loadContext) : base(loadContext) { }
private static Assembly ResolveAssembly(AssemblyLoadContext sender, AssemblyName assembly) { string assemblyFilename = assembly.Name + ".dll"; return sender.LoadFromAssemblyPath(Path.Combine(Path.GetTempPath(), assemblyFilename)); }
/// <summary> /// Executes a LoadFrom in the app domain LoaderClass has been loaded into. Attempts to load a given assembly, looking in the /// given paths & the current directory. /// </summary> /// <param name="path">The assembly to load</param> /// <param name="paths">Paths to search for the given assembly</param> public void LoadFrom(string path, string[] paths #if !PROJECTK_BUILD , ReliabilityFramework rf #endif ) { #if !PROJECTK_BUILD myRf = rf; AssemblyName an = new AssemblyName(); an.CodeBase = assembly = path; //register AssemblyLoad and DomainUnload events AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(this.UnloadOnAssemblyLoad); AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.UnloadOnDomainUnload); #else AssemblyLoadContext alc = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); #endif try { #if !PROJECTK_BUILD assem = Assembly.Load(an); #else assembly = path; assem = alc.LoadFromAssemblyPath(assembly); #endif } catch { try { FileInfo fi = new FileInfo(path); assembly = fi.FullName; #if !PROJECTK_BUILD an = new AssemblyName(); an.CodeBase = assembly; assem = Assembly.Load(an); #else assem = alc.LoadFromAssemblyPath(assembly); #endif } catch { if (paths != null) { foreach (string basePath in paths) { try { assembly = ReliabilityConfig.ConvertPotentiallyRelativeFilenameToFullPath(basePath, path); #if !PROJECTK_BUILD an = new AssemblyName(); an.CodeBase = assembly; assem = Assembly.Load(an); #else assem = alc.LoadFromAssemblyPath(assembly); #endif break; } catch { } } } } } }
private static IntPtr InternalGetFunctionPointer(AssemblyLoadContext alc, string typeName, string methodName, IntPtr delegateTypeNative) { // Create a resolver callback for types. Func <AssemblyName, Assembly> resolver = name => alc.LoadFromAssemblyName(name); // Determine the signature of the type. There are 3 possibilities: // * No delegate type was supplied - use the default (i.e. ComponentEntryPoint). // * A sentinel value was supplied - the function is marked UnmanagedCallersOnly. This means // a function pointer can be returned without creating a delegate. // * A delegate type was supplied - Load the type and create a delegate for that method. Type?delegateType; if (delegateTypeNative == IntPtr.Zero) { delegateType = typeof(ComponentEntryPoint); } else if (delegateTypeNative == (IntPtr)(-1)) { delegateType = null; } else { string delegateTypeName = MarshalToString(delegateTypeNative, nameof(delegateTypeNative)); delegateType = Type.GetType(delegateTypeName, resolver, null, throwOnError: true) !; } // Get the requested type. Type type = Type.GetType(typeName, resolver, null, throwOnError: true) !; IntPtr functionPtr; if (delegateType == null) { // Match search semantics of the CreateDelegate() function below. BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; MethodInfo? methodInfo = type.GetMethod(methodName, bindingFlags); if (methodInfo == null) { throw new MissingMethodException(typeName, methodName); } // Verify the function is properly marked. if (null == methodInfo.GetCustomAttribute <UnmanagedCallersOnlyAttribute>()) { throw new InvalidOperationException(SR.InvalidOperation_FunctionMissingUnmanagedCallersOnly); } functionPtr = methodInfo.MethodHandle.GetFunctionPointer(); } else { Delegate d = Delegate.CreateDelegate(delegateType, type, methodName) !; functionPtr = Marshal.GetFunctionPointerForDelegate(d); lock (s_delegates) { // Keep a reference to the delegate to prevent it from being garbage collected s_delegates[functionPtr] = d; } } return(functionPtr); }
public AssemblyLoadContextWrapper(AssemblyLoadContext ctx) { this.ctx = ctx; }
private Assembly LoadAssembly(AssemblyLoadContext context, string name) => context.LoadFromAssemblyName(new AssemblyName(name));
/// <summary> /// The handler for the Resolving event /// </summary> private Assembly Resolve(AssemblyLoadContext loadContext, AssemblyName assemblyName) { // Probe the assembly cache Assembly asmLoaded; if (TryGetAssemblyFromCache(assemblyName, out asmLoaded)) { return(asmLoaded); } // Prepare to load the assembly lock (s_syncObj) { // Probe the cache again in case it's already loaded if (TryGetAssemblyFromCache(assemblyName, out asmLoaded)) { return(asmLoaded); } // Search the specified assembly in probing paths, and load it through 'LoadFromAssemblyPath' if the file exists and matches the requested AssemblyName. // If the CultureName of the requested assembly is not NullOrEmpty, then it's a resources.dll and we need to search corresponding culture sub-folder. bool isAssemblyFileFound = false, isAssemblyFileMatching = false; string asmCultureName = assemblyName.CultureName ?? string.Empty; string asmFilePath = null; for (int i = 0; i < _probingPaths.Count; i++) { string probingPath = _probingPaths[i]; string asmCulturePath = Path.Combine(probingPath, asmCultureName); for (int k = 0; k < _extensions.Length; k++) { string asmFileName = assemblyName.Name + _extensions[k]; asmFilePath = Path.Combine(asmCulturePath, asmFileName); if (File.Exists(asmFilePath)) { isAssemblyFileFound = true; AssemblyName asmNameFound = GetAssemblyName(asmFilePath); if (IsAssemblyMatching(assemblyName, asmNameFound)) { isAssemblyFileMatching = true; break; } } } if (isAssemblyFileFound && isAssemblyFileMatching) { break; } } // We failed to find the assembly file; or we found the file, but the assembly file doesn't match the request. // In this case, return null so that other Resolving event handlers can kick in to resolve the request. if (!isAssemblyFileFound || !isAssemblyFileMatching) { return(null); } asmLoaded = asmFilePath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) ? loadContext.LoadFromNativeImagePath(asmFilePath, null) : loadContext.LoadFromAssemblyPath(asmFilePath); if (asmLoaded != null) { // Add the loaded assembly to the cache s_assemblyCache.TryAdd(assemblyName.Name, asmLoaded); } } // Raise AssemblyLoad event OnAssemblyLoaded(asmLoaded); return(asmLoaded); }
private void RegisterShutdownHook() { var currentAssembly = typeof(AWSLoggerCore).GetTypeInfo().Assembly; AssemblyLoadContext.GetLoadContext(currentAssembly).Unloading += this.OnAssemblyLoadContextUnloading; }
/// <summary> /// Create a new Editor Services loader. /// </summary> /// <param name="logger">The host logger to use.</param> /// <param name="hostConfig">The host configuration to start editor services with.</param> /// <param name="sessionFileWriter">The session file writer to write the session file with.</param> /// <returns></returns> public static EditorServicesLoader Create( HostLogger logger, EditorServicesConfig hostConfig, ISessionFileWriter sessionFileWriter, IReadOnlyCollection <IDisposable> loggersToUnsubscribe) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (hostConfig == null) { throw new ArgumentNullException(nameof(hostConfig)); } #if CoreCLR // In .NET Core, we add an event here to redirect dependency loading to the new AssemblyLoadContext we load PSES' dependencies into logger.Log(PsesLogLevel.Verbose, "Adding AssemblyResolve event handler for new AssemblyLoadContext dependency loading"); var psesLoadContext = new PsesLoadContext(s_psesDependencyDirPath); if (hostConfig.LogLevel == PsesLogLevel.Diagnostic) { AppDomain.CurrentDomain.AssemblyLoad += (object sender, AssemblyLoadEventArgs args) => { logger.Log( PsesLogLevel.Diagnostic, $"Loaded into load context {AssemblyLoadContext.GetLoadContext(args.LoadedAssembly)}: {args.LoadedAssembly}"); }; } AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext defaultLoadContext, AssemblyName asmName) => { logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {asmName}"); // We only want the Editor Services DLL; the new ALC will lazily load its dependencies automatically if (!string.Equals(asmName.Name, "Microsoft.PowerShell.EditorServices", StringComparison.Ordinal)) { return(null); } string asmPath = Path.Combine(s_psesDependencyDirPath, $"{asmName.Name}.dll"); logger.Log(PsesLogLevel.Verbose, "Loading PSES DLL using new assembly load context"); return(psesLoadContext.LoadFromAssemblyPath(asmPath)); }; #else // In .NET Framework we add an event here to redirect dependency loading in the current AppDomain for PSES' dependencies logger.Log(PsesLogLevel.Verbose, "Adding AssemblyResolve event handler for dependency loading"); if (hostConfig.LogLevel == PsesLogLevel.Diagnostic) { AppDomain.CurrentDomain.AssemblyLoad += (object sender, AssemblyLoadEventArgs args) => { logger.Log( PsesLogLevel.Diagnostic, $"Loaded {args.LoadedAssembly.GetName()}"); }; } // Unlike in .NET Core, we need to be look for all dependencies in .NET Framework, not just PSES.dll AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) => { logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {args.Name}"); var asmName = new AssemblyName(args.Name); string asmPath = Path.Combine(s_psesDependencyDirPath, $"{asmName.Name}.dll"); if (!File.Exists(asmPath)) { return(null); } logger.Log(PsesLogLevel.Diagnostic, $"Loading {args.Name} from PSES dependency dir into LoadFrom context"); return(Assembly.LoadFrom(asmPath)); }; #endif return(new EditorServicesLoader(logger, hostConfig, sessionFileWriter, loggersToUnsubscribe)); }
internal void OnAssemblyLoadContextUnloading(AssemblyLoadContext obj) { this.Close(); }
partial void SubscribeToAssemblyLoadContextUnload() { AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()).Unloading += SqlConnectionFactoryAssemblyLoadContext_Unloading; }
private static void UnloadServer(AssemblyLoadContext obj) { try { lock (ServerLocker) { var copyGlobalServer = _globalServer; _globalServer = null; if (copyGlobalServer == null) { return; } try { using (copyGlobalServer.ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context)) using (context.OpenReadTransaction()) { var databases = copyGlobalServer .ServerStore .Cluster .ItemsStartingWith(context, Constants.Documents.Prefix, 0, int.MaxValue) .ToList(); if (databases.Count > 0) { var sb = new StringBuilder(); sb.AppendLine("List of non-deleted databases:"); foreach (var t in databases) { sb .Append("- ") .AppendLine(t.ItemName.Substring(Constants.Documents.Prefix.Length)); } Console.WriteLine(sb.ToString()); } } } catch (Exception e) { Console.WriteLine($"Could not retrieve list of non-deleted databases. Exception: {e}"); } copyGlobalServer.Dispose(); GC.Collect(2); GC.WaitForPendingFinalizers(); var exceptionAggregator = new ExceptionAggregator("Failed to cleanup test databases"); RavenTestHelper.DeletePaths(GlobalPathsToDelete, exceptionAggregator); exceptionAggregator.ThrowIfNeeded(); } } catch (Exception e) { Console.WriteLine(e); } }
private Assembly ResolveAssembly(AssemblyLoadContext context, AssemblyName assembly) { string assemblyFilename = assembly.Name + ".dll"; return(context.LoadFromAssemblyPath(Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), assemblyFilename))); }
private static void DefaultOnUnloading(AssemblyLoadContext assemblyLoadContext) { Log.Warning("Unloading process"); ExitEvent.Set(); }
private Assembly Default_Resolving(AssemblyLoadContext arg1, AssemblyName arg2) { return(Load(arg2)); }
internal void CreateAssembliesContext() { assembliesContext = new AssemblyLoadContext("UnrealEngine", true); Core.assembliesContextWeakReference = new WeakReference(assembliesContext, trackResurrection: true); }
public static void GetAssemblyNameTest_NullParameter() { Assert.Throws <ArgumentNullException>(() => AssemblyLoadContext.GetAssemblyName(null)); }
private static void OnShutdown(AssemblyLoadContext obj) { _Shutdown.Set(); }
public static void LoadRefEmitAssemblyInLoadContext(AssemblyLoadContext loadContext, AssemblyBuilderAccess builderType) { // Load this assembly in custom LoadContext var assemblyNameStr = "System.Runtime.Loader.Noop.Assembly.dll"; // Load the assembly in the specified load context var asmTargetAsm = loadContext.LoadFromAssemblyPath(Path.Combine(s_loadFromPath, assemblyNameStr)); var loadedContext = AssemblyLoadContext.GetLoadContext(asmTargetAsm); // Get reference to the helper method that will RefEmit an assembly and return reference to it. Type type = asmTargetAsm.GetType("System.Runtime.Loader.Tests.TestClass"); var method = System.Reflection.TypeExtensions.GetMethod(type, "GetRefEmitAssembly"); // Use the helper to generate an assembly var assemblyNameRefEmit = "RefEmitTestAssembly"; var asmRefEmitLoaded = (Assembly)method.Invoke(null, new object[] {assemblyNameRefEmit, builderType}); Assert.NotNull(asmRefEmitLoaded); // Assert that Dynamically emitted assemblies do not have a load context associated with them. var loadContextRefEmitAssembly = AssemblyLoadContext.GetLoadContext(asmRefEmitLoaded); Assert.Equal(null, loadContextRefEmitAssembly); // Invoke the method that will trigger a static load in the dynamically generated assembly. Type typeRefEmit = asmRefEmitLoaded.GetType("RefEmitTestType"); method = System.Reflection.TypeExtensions.GetMethod(typeRefEmit, "LoadStaticAssembly"); Assert.NotNull(method); // Invoke the method to load the current assembly from the temp location var assemblyStaticToLoad = typeof(RefEmitLoadContext).GetTypeInfo().Assembly.GetName().Name; var asmRefEmitLoadedStatic = method.Invoke(null, new object[] {assemblyStaticToLoad}); Assert.NotNull(asmRefEmitLoadedStatic); // Load context of the statically loaded assembly is the custom load context in which dynamic assembly was created Assert.Equal(loadContext, AssemblyLoadContext.GetLoadContext((Assembly)asmRefEmitLoadedStatic)); }
public override AssemblyLoadContext CreateAssemblyLoadContextWithPolicy(string appDomainName, Evidence evidence, AppDomainSetup setupInfo, SandboxCasPolicySettings casSettings) { AssemblyLoadContext assemblyLoadContext = new AssemblyLoadContext(appDomainName, true); return(assemblyLoadContext); }
private static Assembly ResolveNullAssembly(AssemblyLoadContext sender, AssemblyName assembly) { return null; }
public static void InitializeDefaultContext(AssemblyLoadContext context);