コード例 #1
0
    public static void GetLoadContextForDynamicAssembly(bool isCollectible)
    {
        try
        {
            Console.WriteLine($"{nameof(GetLoadContextForDynamicAssembly)}; isCollectible={isCollectible}");

            AssemblyLoadContext alc = new AssemblyLoadContext($"ALC - {isCollectible}", isCollectible);
            AssemblyBuilder     assemblyBuilder;
            AssemblyName        assemblyName = new AssemblyName($"DynamicAssembly_{Guid.NewGuid():N}");

            using (alc.EnterContextualReflection())
            {
                assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect);
            }

            AssemblyLoadContext?context = AssemblyLoadContext.GetLoadContext(assemblyBuilder);

            Assert(context != null);
            Assert(alc == context);
            Assert(alc.Assemblies.Any(a => AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyName)));
        }
        catch (Exception e)
        {
            Assert(false, e.ToString());
        }
    }
コード例 #2
0
ファイル: ContextualReflection.cs プロジェクト: z77ma/runtime
        void TestAssemblyLoad(bool isolated, Func <string, Assembly> assemblyLoad)
        {
            TestResolveMissingAssembly(isolated, (string assemblyName) => assemblyLoad(assemblyName));

            using (AssemblyLoadContext.EnterContextualReflection(null))
            {
                Assembly assembly = assemblyLoad("ContextualReflection");

                Assert.Equal(isolated ? alc : AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(assembly));

                Assembly depends = assemblyLoad("ContextualReflectionDependency");

                Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(depends));
            }
            using (AssemblyLoadContext.Default.EnterContextualReflection())
            {
                Assembly assembly = assemblyLoad("ContextualReflection");

                Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(assembly));

                Assembly depends = assemblyLoad("ContextualReflectionDependency");

                Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(depends));
            }
            using (alc.EnterContextualReflection())
            {
                Assembly assembly = assemblyLoad("ContextualReflection");

                Assert.Equal(alc, AssemblyLoadContext.GetLoadContext(assembly));

                Assembly depends = assemblyLoad("ContextualReflectionDependency");

                Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(depends));
            }
        }
コード例 #3
0
        void EnterContextualReflectionUsingNestedImmutableDispose()
        {
            AssemblyLoadContext context;

            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            context = _fixture.defaultAlc;
            using (var scopeDefault = context.EnterContextualReflection())
            {
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
                AssemblyLoadContext nestedContext = _fixture.isolatedAlc;
                using (var scopeIsolated = nestedContext.EnterContextualReflection())
                {
                    Assert.Equal(nestedContext, AssemblyLoadContext.CurrentContextualReflectionContext);

                    scopeDefault.Dispose();
                    Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
                    scopeIsolated.Dispose();
                    Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
                    scopeDefault.Dispose();
                    Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
                }
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
            }
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
        }
コード例 #4
0
        void InstanceEnterContextualReflectionUsingNested()
        {
            AssemblyLoadContext context;

            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            context = _fixture.defaultAlc;
            using (context.EnterContextualReflection())
            {
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
                AssemblyLoadContext nestedContext = _fixture.isolatedAlc;
                using (nestedContext.EnterContextualReflection())
                {
                    Assert.Equal(nestedContext, AssemblyLoadContext.CurrentContextualReflectionContext);
                }
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
            }
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            context = _fixture.isolatedAlc;
            using (context.EnterContextualReflection())
            {
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
                AssemblyLoadContext nestedContext = _fixture.defaultAlc;
                using (nestedContext.EnterContextualReflection())
                {
                    Assert.Equal(nestedContext, AssemblyLoadContext.CurrentContextualReflectionContext);
                }
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
            }

            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
        }
コード例 #5
0
ファイル: ContextualReflection.cs プロジェクト: z77ma/runtime
        void VerifyContextualReflectionProxy()
        {
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            using (alc.EnterContextualReflection())
            {
                Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
                using (AssemblyLoadContext.Default.EnterContextualReflection())
                {
                    Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.CurrentContextualReflectionContext);
                    using (AssemblyLoadContext.EnterContextualReflection(null))
                    {
                        Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
                        using (AssemblyLoadContext.EnterContextualReflection(alcAssembly))
                        {
                            Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
                        }
                        Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
                    }
                    Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.CurrentContextualReflectionContext);
                }
                Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
            }
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
        }
コード例 #6
0
        void StaticEnterContextualReflectionUsingBasic()
        {
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            AssemblyLoadContext context  = null;
            Assembly            assembly = null;

            using (AssemblyLoadContext.EnterContextualReflection(assembly))
            {
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
            }
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            context  = _fixture.defaultAlc;
            assembly = _fixture.defaultAlcAssembly;
            using (AssemblyLoadContext.EnterContextualReflection(assembly))
            {
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
            }
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            context  = _fixture.isolatedAlc;
            assembly = _fixture.isolatedAlcAssembly;
            using (AssemblyLoadContext.EnterContextualReflection(assembly))
            {
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);
            }
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
        }
コード例 #7
0
        public void LoadPreloadedExternalAssembly()
        {
            AssemblyLoadContext testAlc        = new AssemblyLoadContext(nameof(LoadPreloadedExternalAssembly));
            Assembly            pluginAssembly = testAlc.LoadFromAssemblyPath(Path.Join(DeploymentUtilities.ExecutableLocation, "PluginLibrary.dll"));

            using var scope = testAlc.EnterContextualReflection();
            ValidateAssemblyLoad("PluginLibrary");
        }
コード例 #8
0
        public void LoadPreloadedAssemblyFromStream()
        {
            AssemblyLoadContext testAlc = new AssemblyLoadContext(nameof(LoadPreloadedExternalAssembly));

            using var fileStream = File.OpenRead(Path.Join(DeploymentUtilities.ExecutableLocation, "PluginLibrary.dll"));
            Assembly assembly = testAlc.LoadFromStream(fileStream);

            using var scope = testAlc.EnterContextualReflection();
            ValidateAssemblyLoad("PluginLibrary");
        }
コード例 #9
0
        void TestDefineDynamicAssembly(bool collectibleContext, AssemblyBuilderAccess assemblyBuilderAccess)
        {
            AssemblyLoadContext assemblyLoadContext = collectibleContext ? new AssemblyLoadContext("DynamicAssembly Collectable context", true) : AssemblyLoadContext.Default;
            AssemblyName        dynamicAssemblyName = new AssemblyName("DynamicAssembly");

            using (assemblyLoadContext.EnterContextualReflection())
            {
                AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, assemblyBuilderAccess);
            }

            Assert.IsTrue(assemblyLoadContext.Assemblies.Any(a => AssemblyName.ReferenceMatchesDefinition(a.GetName(), dynamicAssemblyName)));
        }
コード例 #10
0
ファイル: ContextualReflection.cs プロジェクト: z77ma/runtime
        void TestDefineDynamicAssembly(bool collectibleContext, AssemblyBuilderAccess assemblyBuilderAccess)
        {
            AssemblyLoadContext assemblyLoadContext = collectibleContext ? new AssemblyLoadContext("DynamicAssembly Collectable context", true) : AssemblyLoadContext.Default;
            AssemblyBuilder     assemblyBuilder;

            using (assemblyLoadContext.EnterContextualReflection())
            {
                assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName($"DynamicAssembly_{Guid.NewGuid():N}"), assemblyBuilderAccess);
            }

            AssemblyLoadContext context = AssemblyLoadContext.GetLoadContext(assemblyBuilder);

            Assert.Equal(assemblyLoadContext, context);
            Assert.True(assemblyLoadContext.Assemblies.Any(a => AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyBuilder.GetName())));
        }
コード例 #11
0
        static public IDisposable EnterContextualReflection(Assembly activating)
        {
#if AssemblyLoadContextContextualReflectionFacade
            return(AssemblyLoadContext.EnterContextualReflection(activating));
#else
            Type t = typeof(AssemblyLoadContext);

            object result = t.InvokeMember("EnterContextualReflection",
                                           BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static,
                                           null,
                                           null,
                                           new object [] { activating });

            return((IDisposable)result);
#endif
        }
コード例 #12
0
        public void RunAssemblyTests(Assembly assembly)
        {
            using AssemblyLoadContext.ContextualReflectionScope scope = AssemblyLoadContext.EnterContextualReflection(assembly);

            using ManualResetEvent testsCompleted = new ManualResetEvent(false);
            using AssemblyRunner runner           = AssemblyRunner.WithoutAppDomain(assembly.Location);

            runner.OnTestFailed += info =>
            {
                this.ProjectData.Points.TryGetValue(info.TestDisplayName, out HashSet <string>?points);

                this.AddTestResult(MethodTestResult.FromFail(info, points));
            };

            runner.OnTestPassed += info =>
            {
                this.ProjectData.Points.TryGetValue(info.TestDisplayName, out HashSet <string>?points);

                this.AddTestResult(MethodTestResult.FromSuccess(info, points));
            };

            runner.OnExecutionComplete += info =>
            {
                testsCompleted.Set();
            };

            //This is non blocking call!
            runner.Start();

            //We don't want to exit before all of the tests have ran
            //This will be signaled once all of the tests have been ran
            testsCompleted.WaitOne();

            //OnExecutionComplete is invoked before setting the Status so spin here until it changes
            SpinWait.SpinUntil(() => runner.Status == AssemblyRunnerStatus.Idle);

            //Give up the time slice
            //Travis sometimes fails inside the xUnit thread pool while trying to wait for completion
            //Try to fix this by trying to give the time slice to the thread pool thread
            Thread.Sleep(1);
        }
コード例 #13
0
ファイル: ContextualReflection.cs プロジェクト: z77ma/runtime
 void TestResolveMissingAssembly(bool isolated, Action <string> action, bool skipNullIsolated = false)
 {
     using (AssemblyLoadContext.EnterContextualReflection(null))
     {
         TestResolve.Assert(ResolveEvents.ExpectedEvent, () => action("TestDefaultLoad"));
         if (!skipNullIsolated)
         {
             TestResolve.Assert(isolated ? ResolveEvents.ExpectedEvent : ResolveEvents.NoEvent, () => action("TestIsolatedLoad"));
         }
     }
     using (AssemblyLoadContext.Default.EnterContextualReflection())
     {
         TestResolve.Assert(ResolveEvents.ExpectedEvent, () => action("TestDefaultLoad"));
         TestResolve.Assert(ResolveEvents.NoEvent, () => action("TestIsolatedLoad"));
     }
     using (alc.EnterContextualReflection())
     {
         TestResolve.Assert(ResolveEvents.ExpectedEvent, () => action("TestDefaultLoad"));
         TestResolve.Assert(ResolveEvents.ExpectedEvent, () => action("TestIsolatedLoad"));
     }
 }
コード例 #14
0
        void StaticEnterContextualReflectionUsingEarlyDispose()
        {
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            AssemblyLoadContext context  = null;
            Assembly            assembly = null;

            using (var scope = AssemblyLoadContext.EnterContextualReflection(assembly))
            {
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);

                scope.Dispose();
                Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
            }
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            context  = _fixture.defaultAlc;
            assembly = _fixture.defaultAlcAssembly;
            using (var scope = AssemblyLoadContext.EnterContextualReflection(assembly))
            {
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);

                scope.Dispose();
                Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
            }
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            context  = _fixture.isolatedAlc;
            assembly = _fixture.isolatedAlcAssembly;
            using (var scope = AssemblyLoadContext.EnterContextualReflection(assembly))
            {
                Assert.Equal(context, AssemblyLoadContext.CurrentContextualReflectionContext);

                scope.Dispose();
                Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
            }
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
        }
コード例 #15
0
        static public IDisposable EnterContextualReflection(Assembly activating)
        {
#if AssemblyLoadContextContextualReflectionFacade
            return(AssemblyLoadContext.EnterContextualReflection(activating));
#else
            Type t = typeof(AssemblyLoadContext);

            try
            {
                object result = t.InvokeMember("EnterContextualReflection",
                                               BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static,
                                               null,
                                               null,
                                               new object [] { activating });
                return((IDisposable)result);
            }
            catch (Exception ex)
            {
                ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
            }
            return(null);
#endif
        }
コード例 #16
0
        public static void Main(string[] args)
        {
            const string envName         = "_DOTNET_WATCH_APP_ASSEMBLY_PATH";
            var          appAssemblyPath = Environment.GetEnvironmentVariable(envName) ??
                                           throw new InvalidOperationException($"No value found for environment variable '{envName}'.");

            var observer = new Observer();

            using var _ = DiagnosticListener.AllListeners.Subscribe(observer);

            // Microsoft.Extensions.DotNetApplier's startup hook emulates Control-C to terminate the running app when
            // it sees changes to Startup.cs / Program.cs during a hot reload session.
            // We need to differentiate between the emulated Control-C and a Control-C performed by the user on the terminal.
            // We use a DiagnosticListener to signal any time the StartupHook emulates Control-C, so that we know
            // when it is not-signaled, it must be a real Control-C.

            var first = true;

            while (observer.EmulatedControlC)
            {
                observer.EmulatedControlC = false;
                if (!first)
                {
                    Console.WriteLine("[watch] Application restarting because changes were detected to the app's initialization code.");
                }
                first = false;

                var currentLoadContext = new HotRestartLoadContext();
                var mainAssembly       = currentLoadContext.LoadFromAssemblyPath(appAssemblyPath);
                // See https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/AssemblyLoadContext.ContextualReflection.md for details.
                using var __ = AssemblyLoadContext.EnterContextualReflection(mainAssembly);

                mainAssembly.EntryPoint !.Invoke(null, new object[] { args });
                currentLoadContext.Unload();
            }
        }
コード例 #17
0
 public void SetPreConditions()
 {
     AssemblyLoadContext.EnterContextualReflection(null);
 }
コード例 #18
0
ファイル: ContextualReflection.cs プロジェクト: z77ma/runtime
 void TestMockAssemblyThrows()
 {
     Exception e = AssertExtensions.ThrowsArgumentException("activating", () => AssemblyLoadContext.EnterContextualReflection(new MockAssembly()));
 }
コード例 #19
0
ファイル: ContextualReflection.cs プロジェクト: z77ma/runtime
        void TestActivatorCreateInstance(bool isolated)
        {
            TestResolveMissingAssembly(isolated, (string assemblyName) => Activator.CreateInstance(assemblyName, "MyType"));
            TestResolveMissingAssembly(isolated,
                                       (string assemblyName) => Activator.CreateInstance("System.Private.CoreLib", string.Format("System.Collections.Generic.List`1[[MyType, {0}]]", assemblyName)),
                                       skipNullIsolated: true);

            TestResolveMissingAssembly(isolated,
                                       (string assemblyName) => Activator.CreateInstance("ContextualReflection", string.Format("ContextualReflectionTest.AGenericClass`1[[MyType, {0}]]", assemblyName)));

            Assembly assembly = Assembly.GetExecutingAssembly();

            using (AssemblyLoadContext.EnterContextualReflection(null))
            {
                {
                    ObjectHandle objectHandle = Activator.CreateInstance(null, "ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program]]");
                    Type         g            = objectHandle.Unwrap().GetType();

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(assembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(Assembly.GetExecutingAssembly(), g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(typeof(Program), g.GenericTypeArguments[0]);
                }
                {
                    ObjectHandle objectHandle = Activator.CreateInstance(null, "ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]]");
                    Type         g            = objectHandle.Unwrap().GetType();

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(assembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(Assembly.GetExecutingAssembly(), g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(typeof(Program), g.GenericTypeArguments[0]);
                }
                {
                    ObjectHandle objectHandle = Activator.CreateInstance("ContextualReflection", "ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]]");
                    Type         g            = objectHandle.Unwrap().GetType();

                    Assembly expectedAssembly = assembly;

                    Assert.NotNull(g);
                    Assert.Equal(expectedAssembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                }
                {
                    Assembly expectedAssembly = alcAssembly;

                    Assembly mscorlib = typeof(System.Collections.Generic.List <string>).Assembly;

                    ObjectHandle objectHandle = Activator.CreateInstance(mscorlib.GetName().Name, "System.Collections.Generic.List`1[[ContextualReflectionTest.Program, ContextualReflection]]");
                    Type         m            = objectHandle.Unwrap().GetType();

                    Assert.NotNull(m);
                    Assert.Equal(mscorlib, m.Assembly);
                    Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(m.GenericTypeArguments[0].Assembly));
                }
            }
            using (AssemblyLoadContext.Default.EnterContextualReflection())
            {
                {
                    ObjectHandle objectHandle = Activator.CreateInstance(null, "ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program]]");
                    Type         g            = objectHandle.Unwrap().GetType();

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(assembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(Assembly.GetExecutingAssembly(), g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(typeof(Program), g.GenericTypeArguments[0]);
                }
                {
                    ObjectHandle objectHandle = Activator.CreateInstance(null, "ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]]");
                    Type         g            = objectHandle.Unwrap().GetType();

                    Assembly expectedAssembly = defaultAssembly;

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                }
                {
                    ObjectHandle objectHandle = Activator.CreateInstance("ContextualReflection", "ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]]");
                    Type         g            = objectHandle.Unwrap().GetType();

                    Assembly expectedAssembly = defaultAssembly;

                    Assert.NotNull(g);
                    Assert.Equal(expectedAssembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                }
                {
                    Assembly mscorlib = typeof(System.Collections.Generic.List <string>).Assembly;

                    ObjectHandle objectHandle = Activator.CreateInstance(mscorlib.GetName().Name, "System.Collections.Generic.List`1[[ContextualReflectionTest.Program, ContextualReflection]]");
                    Type         m            = objectHandle.Unwrap().GetType();

                    Assembly expectedAssembly = mscorlib;

                    Assert.NotNull(m);
                    Assert.Equal(expectedAssembly, m.Assembly);
                    Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(m.GenericTypeArguments[0].Assembly));
                }
            }
            using (alc.EnterContextualReflection())
            {
                {
                    ObjectHandle objectHandle = Activator.CreateInstance(null, "ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program]]");
                    Type         g            = objectHandle.Unwrap().GetType();

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(assembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(Assembly.GetExecutingAssembly(), g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(typeof(Program), g.GenericTypeArguments[0]);
                }
                {
                    ObjectHandle objectHandle = Activator.CreateInstance(null, "ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]]");
                    Type         g            = objectHandle.Unwrap().GetType();

                    Assembly expectedAssembly = alcAssembly;

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                }
                {
                    ObjectHandle objectHandle = Activator.CreateInstance("ContextualReflection", "ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]]");
                    Type         g            = objectHandle.Unwrap().GetType();

                    Assembly expectedAssembly = alcAssembly;

                    Assert.NotNull(g);
                    Assert.Equal(expectedAssembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                }
                {
                    Assembly mscorlib = typeof(System.Collections.Generic.List <string>).Assembly;

                    ObjectHandle objectHandle = Activator.CreateInstance(mscorlib.GetName().Name, "System.Collections.Generic.List`1[[ContextualReflectionTest.Program, ContextualReflection]]");
                    Type         m            = objectHandle.Unwrap().GetType();

                    Assert.NotNull(m);
                    Assert.Equal(mscorlib, m.Assembly);
                    Assert.Equal(alc, AssemblyLoadContext.GetLoadContext(m.GenericTypeArguments[0].Assembly));
                }
            }
        }
コード例 #20
0
ファイル: ContextualReflection.cs プロジェクト: z77ma/runtime
        void TestAssemblyGetType(bool isolated)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();

            TestResolveMissingAssembly(isolated,
                                       (string assemblyName) => assembly.GetType(string.Format("ContextualReflectionTest.AGenericClass`1[[MyType, {0}]]", assemblyName)));

            using (AssemblyLoadContext.EnterContextualReflection(null))
            {
                {
                    Type g = assembly.GetType("ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program]]", throwOnError: false);

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(assembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(Assembly.GetExecutingAssembly(), g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(typeof(Program), g.GenericTypeArguments[0]);
                }
                {
                    Type g = assembly.GetType("ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]]", throwOnError: false);

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(assembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(Assembly.GetExecutingAssembly(), g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(typeof(Program), g.GenericTypeArguments[0]);
                }
                {
                    Assembly mscorlib = typeof(System.Collections.Generic.List <string>).Assembly;

                    Type m = mscorlib.GetType("System.Collections.Generic.List`1[[ContextualReflectionTest.Program, ContextualReflection]]", throwOnError: false);

                    Assembly expectedAssembly = mscorlib;

                    Assert.NotNull(m);
                    Assert.Equal(expectedAssembly, m.Assembly);
                    Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(m.GenericTypeArguments[0].Assembly));
                }
            }
            using (AssemblyLoadContext.Default.EnterContextualReflection())
            {
                {
                    Type g = assembly.GetType("ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program]]", throwOnError: false);

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(assembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(Assembly.GetExecutingAssembly(), g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(typeof(Program), g.GenericTypeArguments[0]);
                }
                {
                    Type g = assembly.GetType("ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]]", throwOnError: false);

                    Assembly expectedAssembly = defaultAssembly;

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                }
                {
                    Assembly mscorlib = typeof(System.Collections.Generic.List <string>).Assembly;

                    Type m = mscorlib.GetType("System.Collections.Generic.List`1[[ContextualReflectionTest.Program, ContextualReflection]]", throwOnError: false);

                    Assembly expectedAssembly = mscorlib;

                    Assert.NotNull(m);
                    Assert.Equal(expectedAssembly, m.Assembly);
                    Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(m.GenericTypeArguments[0].Assembly));
                }
            }
            using (alc.EnterContextualReflection())
            {
                {
                    Type g = assembly.GetType("ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program]]", throwOnError: false);

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(assembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(Assembly.GetExecutingAssembly(), g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(typeof(Program), g.GenericTypeArguments[0]);
                }
                {
                    Type g = assembly.GetType("ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]]", throwOnError: false);

                    Assembly expectedAssembly = alcAssembly;

                    Assert.NotNull(g);
                    Assert.Equal(assembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                }
                {
                    Assembly mscorlib = typeof(System.Collections.Generic.List <string>).Assembly;

                    Type m = mscorlib.GetType("System.Collections.Generic.List`1[[ContextualReflectionTest.Program, ContextualReflection]]", throwOnError: false);

                    Assembly expectedAssembly = mscorlib;

                    Assert.NotNull(m);
                    Assert.Equal(expectedAssembly, m.Assembly);
                    Assert.Equal(alc, AssemblyLoadContext.GetLoadContext(m.GenericTypeArguments[0].Assembly));
                }
            }
        }
コード例 #21
0
        internal static Assembly?LoadGeneratedAssembly(Type type, string?defaultNamespace, out XmlSerializerImplementation?contract)
        {
            Assembly?serializer = null;

            contract = null;
            string?serializerName;

            using (AssemblyLoadContext.EnterContextualReflection(type.Assembly))
            {
                // check to see if we loading explicit pre-generated assembly
                object[] attrs = type.GetCustomAttributes(typeof(System.Xml.Serialization.XmlSerializerAssemblyAttribute), false);
                if (attrs.Length == 0)
                {
                    // Guess serializer name: if parent assembly signed use strong name
                    AssemblyName name = type.Assembly.GetName();
                    serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
                    // use strong name
                    name.Name        = serializerName;
                    name.CodeBase    = null;
                    name.CultureInfo = CultureInfo.InvariantCulture;

                    try
                    {
                        serializer = Assembly.Load(name);
                    }
                    catch (Exception e)
                    {
                        if (e is OutOfMemoryException)
                        {
                            throw;
                        }
                    }

                    serializer ??= LoadAssemblyByPath(type, serializerName);

                    if (serializer == null)
                    {
                        if (XmlSerializer.Mode == SerializationMode.PreGenOnly)
                        {
                            throw new Exception(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName));
                        }

                        return(null);
                    }

                    if (!IsSerializerVersionMatch(serializer, type, defaultNamespace))
                    {
                        XmlSerializationEventSource.Log.XmlSerializerExpired(serializerName, type.FullName !);
                        return(null);
                    }
                }
                else
                {
                    System.Xml.Serialization.XmlSerializerAssemblyAttribute assemblyAttribute = (System.Xml.Serialization.XmlSerializerAssemblyAttribute)attrs[0];
                    if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null)
                    {
                        throw new InvalidOperationException(SR.Format(SR.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase"));
                    }

                    // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer
                    if (assemblyAttribute.AssemblyName != null)
                    {
                        serializerName = assemblyAttribute.AssemblyName;
                        serializer     = Assembly.Load(serializerName); // LoadWithPartialName just does this in .Net Core; changing the obsolete call.
                    }
                    else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0)
                    {
                        serializerName = assemblyAttribute.CodeBase;
                        serializer     = Assembly.LoadFrom(serializerName);
                    }
                    else
                    {
                        serializerName = type.Assembly.FullName;
                        serializer     = type.Assembly;
                    }
                    if (serializer == null)
                    {
                        throw new FileNotFoundException(null, serializerName);
                    }
                }
                Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract");
                contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType) !;
                if (contract.CanSerialize(type))
                {
                    return(serializer);
                }
            }

            return(null);
        }
コード例 #22
0
ファイル: ContextualReflection.cs プロジェクト: z77ma/runtime
        void VerifyBadContextualReflectionUsage()
        {
            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            {
                IDisposable alcScope = alc.EnterContextualReflection();
                Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
                alcScope.Dispose();
            }

            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            {
                IDisposable alcScope = alc.EnterContextualReflection();
                Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
                alcScope.Dispose();
                alcScope.Dispose();
            }

            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            {
                IDisposable alcScope = alc.EnterContextualReflection();
                Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
                IDisposable defaultScope = AssemblyLoadContext.Default.EnterContextualReflection();
                Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.CurrentContextualReflectionContext);
                defaultScope.Dispose();
                Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
                alcScope.Dispose();
            }

            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            {
                IDisposable alcScope = alc.EnterContextualReflection();
                Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
                IDisposable defaultScope = AssemblyLoadContext.Default.EnterContextualReflection();
                Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.CurrentContextualReflectionContext);

                alcScope.Dispose();
                Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

                defaultScope.Dispose();
                Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
                alcScope.Dispose();
            }

            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);

            {
                IDisposable alcScope = alc.EnterContextualReflection();
                Assert.Equal(alc, AssemblyLoadContext.CurrentContextualReflectionContext);
                try
                {
                    IDisposable defaultScope = AssemblyLoadContext.EnterContextualReflection(null);
                    Assert.Equal(null, AssemblyLoadContext.CurrentContextualReflectionContext);

                    throw new InvalidOperationException();
                }
                catch
                {
                }
            }

            Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
        }
コード例 #23
0
ファイル: ContextualReflection.cs プロジェクト: z77ma/runtime
        void TestTypeGetType(bool isolated, Func <string, System.Type> typeGetType)
        {
            TestResolveMissingAssembly(isolated, (string assemblyName) => typeGetType(string.Format("MyType, {0}", assemblyName)));

            using (AssemblyLoadContext.EnterContextualReflection(null))
            {
                {
                    Type p = typeGetType("ContextualReflectionTest.Program");

                    Assembly expectedAssembly = Assembly.GetExecutingAssembly();

                    Assert.NotNull(p);
                    Assert.Equal(expectedAssembly, p.Assembly);
                    Assert.Equal(typeof(Program), p);
                }
                {
                    Type p = typeGetType("ContextualReflectionTest.Program, ContextualReflection");

                    Assembly expectedAssembly = Assembly.GetExecutingAssembly();

                    Assert.NotNull(p);
                    Assert.Equal(expectedAssembly, p.Assembly);
                    Assert.Equal(typeof(Program), p);
                }
                {
                    Type g = typeGetType("ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]], ContextualReflection");

                    Assembly expectedAssembly = Assembly.GetExecutingAssembly();

                    Assert.NotNull(g);
                    Assert.Equal(expectedAssembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(typeof(Program), g.GenericTypeArguments[0]);
                    Assert.Equal(isolated ? alc : AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(g.GenericTypeArguments[0].Assembly));
                }
            }
            using (AssemblyLoadContext.Default.EnterContextualReflection())
            {
                {
                    Type p = typeGetType("ContextualReflectionTest.Program");

                    Assembly expectedAssembly = Assembly.GetExecutingAssembly();

                    Assert.NotNull(p);
                    Assert.Equal(expectedAssembly, p.Assembly);
                    Assert.Equal(typeof(Program), p);
                }
                {
                    Type p = typeGetType("ContextualReflectionTest.Program, ContextualReflection");

                    Assembly expectedAssembly = defaultAssembly;

                    Assert.NotNull(p);
                    Assert.Equal(expectedAssembly, p.Assembly);
                    Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(p.Assembly));
                }
                {
                    Type g = typeGetType("ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]], ContextualReflection");

                    Assembly expectedAssembly = defaultAssembly;

                    Assert.NotNull(g);
                    Assert.Equal(expectedAssembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(g.Assembly));
                    Assert.Equal(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(g.GenericTypeArguments[0].Assembly));
                }
            }
            using (alc.EnterContextualReflection())
            {
                {
                    Type p = typeGetType("ContextualReflectionTest.Program");

                    Assembly expectedAssembly = Assembly.GetExecutingAssembly();

                    Assert.NotNull(p);
                    Assert.Equal(expectedAssembly, p.Assembly);
                    Assert.Equal(typeof(Program), p);
                }
                {
                    Type p = typeGetType("ContextualReflectionTest.Program, ContextualReflection");

                    Assembly expectedAssembly = alcAssembly;

                    Assert.NotNull(p);
                    Assert.Equal(expectedAssembly, p.Assembly);
                    Assert.Equal(alc, AssemblyLoadContext.GetLoadContext(p.Assembly));
                }
                {
                    Type g = typeGetType("ContextualReflectionTest.AGenericClass`1[[ContextualReflectionTest.Program, ContextualReflection]], ContextualReflection");

                    Assembly expectedAssembly = alcAssembly;

                    Assert.NotNull(g);
                    Assert.Equal(expectedAssembly, g.Assembly);
                    Assert.Equal(expectedAssembly, g.GenericTypeArguments[0].Assembly);
                    Assert.Equal(alc, AssemblyLoadContext.GetLoadContext(g.Assembly));
                    Assert.Equal(alc, AssemblyLoadContext.GetLoadContext(g.GenericTypeArguments[0].Assembly));
                }
            }
        }
コード例 #24
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            try
            {
                // Don't block the thread startup thread
                await Task.Yield();

                // Make a file watcher for the project
                var watcher = new FileSystemWatcher(_options.ProjectPath, "*.cs")
                {
                    EnableRaisingEvents = true
                };

                var noopLifetime = new NoopHostLifetime();

                // Run until the host has been shutdown
                while (!cancellationToken.IsCancellationRequested)
                {
                    // Load the application in a new load context
                    var loadContext = new AppLoadContext(_options.DllPath);

                    _logger.LogDebug("Loading {projectName} into load context", _options.ProjectName);

                    var projectAssembly = loadContext.LoadFromAssemblyName(AssemblyName.GetAssemblyName(_options.DllPath));

                    using var reflection = AssemblyLoadContext.EnterContextualReflection(projectAssembly);

                    var type = projectAssembly.GetType($"{_options.ProjectName}.Program");
                    var createHostBuilderMethodInfo = type.GetMethod("CreateHostBuilder", BindingFlags.Static | BindingFlags.Public);

                    var createHostBuilder = (CreateHostBuilderDelegate)Delegate.CreateDelegate(typeof(CreateHostBuilderDelegate), createHostBuilderMethodInfo);

                    // Create a new HostBuilder based on the application
                    var applicationHostBuilder = createHostBuilder(_options.Args);

                    // Override the IServer so that we get Start and Stop application notificaitons
                    applicationHostBuilder.ConfigureServices(services =>
                    {
                        services.AddSingleton <IServer>(_server);

                        // We delegate shutdown to the host, we'll call StopAsync on the application ourselves
                        services.AddSingleton <IHostLifetime>(noopLifetime);
                    });

                    // Build the host for the child application
                    var applicationHost = applicationHostBuilder.Build();

                    _logger.LogDebug("Starting application");

                    // Start the application host
                    await applicationHost.StartAsync(cancellationToken);

                    // Wait for a file change in the target application
                    await WaitForFileChangedAsync(watcher, cancellationToken);

                    _logger.LogDebug("Stopping application");

                    // Shut down the application host
                    await applicationHost.StopAsync();

                    _logger.LogDebug("Application stopped");

                    // Unload the custom load context
                    loadContext.Unload();

                    _logger.LogDebug("Application context unloaded");

                    // For some odd reason this ends the process
                    // GC.Collect();

                    // Don't rebuild if we're shuttind down gracefully
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    _logger.LogDebug("Rebuilding application");

                    // Rebuild the project (without restoring)
                    var exitCode = await RunProcessAsync(new ProcessStartInfo
                    {
                        FileName         = _options.DotNetPath,
                        Arguments        = "build --no-restore",
                        WorkingDirectory = _options.ProjectPath,
                        CreateNoWindow   = false,
                    });

                    _logger.LogDebug("Exit code was {processExitCode}", exitCode);
                }
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Watching loop failed, stopping application.");

                _lifetime.StopApplication();
            }
        }
コード例 #25
0
 void EnterContextualReflectionWithMockAssemblyThrows()
 {
     AssertExtensions.Throws <ArgumentException>("activating", () => AssemblyLoadContext.EnterContextualReflection(new MockAssembly()));
 }
コード例 #26
0
 /// <summary>
 /// Sets the scope used by some System.Reflection APIs which might trigger assembly loading.
 /// <para>
 /// See https://github.com/dotnet/coreclr/blob/v3.0.0/Documentation/design-docs/AssemblyLoadContext.ContextualReflection.md for more details.
 /// </para>
 /// </summary>
 /// <returns></returns>
 public AssemblyLoadContext.ContextualReflectionScope EnterContextualReflection()
 => _context.EnterContextualReflection();