コード例 #1
0
        async Task InitializeInstanceAsync()
        {
            var assemblies = ReadAssembliesFromAddins();
            var caching    = new Caching(assemblies);

            // Try to use cached MEF data
            if (cacheEnabled && caching.CanUse())
            {
                RuntimeComposition = await TryCreateRuntimeCompositionFromCache(caching);
            }

            // Otherwise fallback to runtime discovery.
            if (RuntimeComposition == null)
            {
                RuntimeComposition = await CreateRuntimeCompositionFromDiscovery(caching);

                CachedComposition cacheManager = new CachedComposition();
                caching.Write(RuntimeComposition, cacheManager).Ignore();
            }

            ExportProviderFactory = RuntimeComposition.CreateExportProviderFactory();
            ExportProvider        = ExportProviderFactory.CreateExportProvider();
            HostServices          = MefV1HostServices.Create(ExportProvider.AsExportProvider());
            ExportProviderV1      = NetFxAdapters.AsExportProvider(ExportProvider);
        }
コード例 #2
0
        static async Task CreateAndWrite(CompositionManager.Caching caching)
        {
            var composition = await CompositionManager.CreateRuntimeCompositionFromDiscovery(caching);

            var cacheManager = new CachedComposition();

            await caching.Write(composition, cacheManager);
        }
コード例 #3
0
        static async Task <RuntimeComposition> CreateAndWrite(CompositionManager.Caching caching)
        {
            var(composition, catalog) = await CompositionManager.CreateRuntimeCompositionFromDiscovery(caching);

            var cacheManager = new CachedComposition();

            await caching.Write(composition, catalog, cacheManager);

            return(composition);
        }
コード例 #4
0
            async Task WriteMefCache(RuntimeComposition runtimeComposition, CachedComposition cacheManager)
            {
                using (var timer = Counters.CompositionSave.BeginTiming()) {
                    WriteMefCacheControl(timer);

                    // Serialize the MEF cache.
                    using (var stream = File.Open(MefCacheFile, FileMode.Create)) {
                        await cacheManager.SaveAsync(runtimeComposition, stream);
                    }
                }
            }
コード例 #5
0
        public async Task TestControlCacheFaultInjection(Type injectorType)
        {
            var injector    = (CompositionManager.ICachingFaultInjector)Activator.CreateInstance(injectorType);
            var caching     = GetCaching(injector);
            var composition = await CompositionManager.CreateRuntimeCompositionFromDiscovery(caching);

            var cacheManager = new CachedComposition();

            await caching.Write(composition, cacheManager);

            Assert.IsFalse(caching.CanUse());
        }
コード例 #6
0
        internal static IExportProviderFactory LoadDefault()
        {
            var    cacheManager = new CachedComposition();
            string cachePath    = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "$ConfigurationAssemblyName$");

            using (var cacheStream = File.OpenRead(cachePath))
            {
                return(cacheManager.LoadExportProviderFactoryAsync(cacheStream, Resolver.DefaultInstance).GetAwaiter().GetResult());
            }
        }
コード例 #7
0
        public override bool Execute()
        {
            var resolver  = Resolver.DefaultInstance;
            var discovery = PartDiscovery.Combine(new AttributedPartDiscoveryV1(resolver), new AttributedPartDiscovery(resolver, isNonPublicSupported: true));

            this.CancellationToken.ThrowIfCancellationRequested();

            var parts = discovery.CreatePartsAsync(this.CatalogAssemblies.Select(item => item.ItemSpec)).GetAwaiter().GetResult();

            foreach (var error in parts.DiscoveryErrors)
            {
                this.Log.LogWarningFromException(error);
            }

            this.CancellationToken.ThrowIfCancellationRequested();
            var catalog = ComposableCatalog.Create(resolver)
                          .AddParts(parts.Parts);

            this.CancellationToken.ThrowIfCancellationRequested();
            var configuration = CompositionConfiguration.Create(catalog);

            if (!string.IsNullOrEmpty(this.DgmlOutputPath))
            {
                configuration.CreateDgml().Save(this.DgmlOutputPath);
            }

            this.CancellationToken.ThrowIfCancellationRequested();
            if (!configuration.CompositionErrors.IsEmpty)
            {
                foreach (var error in configuration.CompositionErrors.Peek())
                {
                    this.Log.LogError(error.Message);
                }

                return(false);
            }

            this.CancellationToken.ThrowIfCancellationRequested();

            string cachePath = Path.GetFullPath(this.CompositionCacheFile);

            this.Log.LogMessage("Producing IoC container \"{0}\"", cachePath);
            using (var cacheStream = File.Open(cachePath, FileMode.Create))
            {
                this.CancellationToken.ThrowIfCancellationRequested();
                var runtime = RuntimeComposition.CreateRuntimeComposition(configuration);
                this.CancellationToken.ThrowIfCancellationRequested();
                var runtimeCache = new CachedComposition();
                runtimeCache.SaveAsync(runtime, cacheStream, this.CancellationToken).GetAwaiter().GetResult();
            }

            return(!this.Log.HasLoggedErrors);
        }
コード例 #8
0
        public async Task TestControlCacheFileStaleList()
        {
            var caching     = GetCaching();
            var composition = await CompositionManager.CreateRuntimeCompositionFromDiscovery(caching);

            var cacheManager = new CachedComposition();

            await caching.Write(composition, cacheManager);

            caching.Assemblies.Add(typeof(Console).Assembly);

            Assert.IsFalse(caching.CanUse());
        }
コード例 #9
0
        internal static async Task <RuntimeComposition> TryCreateRuntimeCompositionFromCache(Caching caching)
        {
            var cacheManager = new CachedComposition();

            try {
                using (var cacheStream = caching.OpenCacheStream()) {
                    return(await cacheManager.LoadRuntimeCompositionAsync(cacheStream, StandardResolver));
                }
            } catch (Exception ex) {
                LoggingService.LogError("Could not deserialize MEF cache", ex);
                caching.DeleteFiles();
            }
            return(null);
        }
コード例 #10
0
        async Task InitializeInstanceAsync()
        {
            var timings  = new Dictionary <string, long> ();
            var metadata = new CompositionLoadMetadata(timings);

            using (var timer = Counters.CompositionLoad.BeginTiming(metadata)) {
                var fullTimer = System.Diagnostics.Stopwatch.StartNew();
                var stepTimer = System.Diagnostics.Stopwatch.StartNew();

                var mefAssemblies = ReadAssembliesFromAddins(timer);
                timings ["ReadFromAddins"] = stepTimer.ElapsedMilliseconds;
                stepTimer.Restart();

                var caching = new Caching(mefAssemblies);

                // Try to use cached MEF data

                var canUse = metadata.ValidCache = caching.CanUse();
                if (canUse)
                {
                    LoggingService.LogInfo("Creating MEF composition from cache");
                    RuntimeComposition = await TryCreateRuntimeCompositionFromCache(caching);
                }
                timings ["LoadFromCache"] = stepTimer.ElapsedMilliseconds;
                stepTimer.Restart();

                // Otherwise fallback to runtime discovery.
                if (RuntimeComposition == null)
                {
                    LoggingService.LogInfo("Creating MEF composition from runtime");
                    var(runtimeComposition, catalog) = await CreateRuntimeCompositionFromDiscovery(caching, timer);

                    RuntimeComposition = runtimeComposition;

                    CachedComposition cacheManager = new CachedComposition();
                    caching.Write(RuntimeComposition, catalog, cacheManager).Ignore();
                }
                timings ["LoadRuntimeComposition"] = stepTimer.ElapsedMilliseconds;
                stepTimer.Restart();

                ExportProviderFactory = RuntimeComposition.CreateExportProviderFactory();
                ExportProvider        = ExportProviderFactory.CreateExportProvider();
                HostServices          = MefV1HostServices.Create(ExportProvider.AsExportProvider());
                ExportProviderV1      = NetFxAdapters.AsExportProvider(ExportProvider);

                timings ["CreateServices"] = stepTimer.ElapsedMilliseconds;
                metadata.Duration          = fullTimer.ElapsedMilliseconds;
            }
        }
コード例 #11
0
            internal Task Write(RuntimeComposition runtimeComposition, CachedComposition cacheManager)
            {
                return(Runtime.RunInMainThread(async() => {
                    IdeApp.Exiting += IdeApp_Exiting;

                    saveTask = Task.Run(async() => {
                        try {
                            await WriteMefCache(runtimeComposition, cacheManager);
                        } catch (Exception ex) {
                            LoggingService.LogError("Failed to write MEF cache", ex);
                        }
                    });
                    await saveTask;

                    IdeApp.Exiting -= IdeApp_Exiting;
                    saveTask = null;
                }));
            }
コード例 #12
0
        public async Task ValidateRuntimeCompositionIsValid()
        {
            var mefAssemblies = CompositionManager.ReadAssembliesFromAddins();
            var caching       = new CompositionManager.Caching(mefAssemblies, file => {
                var tmpDir = Path.Combine(Util.TmpDir, "mef", nameof(ValidateRuntimeCompositionIsValid));
                if (Directory.Exists(tmpDir))
                {
                    Directory.Delete(tmpDir, true);
                }
                Directory.CreateDirectory(tmpDir);
                return(Path.Combine(tmpDir, file));
            }, exceptionHandler: new ThrowingHandler());

            var(composition, catalog) = await CompositionManager.CreateRuntimeCompositionFromDiscovery(caching);

            var cacheManager = new CachedComposition();

            await caching.Write(composition, catalog, cacheManager);
        }
コード例 #13
0
ファイル: TestUtilities.cs プロジェクト: v-zbsail/vs-mef
        internal static async Task <ExportProvider> CreateContainerAsync(this CompositionConfiguration configuration, ITestOutputHelper output)
        {
            Requires.NotNull(configuration, nameof(configuration));
            Requires.NotNull(output, nameof(output));

            var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration);

            // Round-trip serialization to make sure the result is equivalent.
            var cacheManager = new CachedComposition();
            var ms           = new MemoryStream();
            await cacheManager.SaveAsync(runtimeComposition, ms);

            output.WriteLine("Cache file size: {0}", ms.Length);
            ms.Position = 0;
            var deserializedRuntimeComposition = await cacheManager.LoadRuntimeCompositionAsync(ms, Resolver);

            Assert.Equal(runtimeComposition, deserializedRuntimeComposition);

            return(runtimeComposition.CreateExportProviderFactory().CreateExportProvider());
        }
コード例 #14
0
        async Task InitializeInstanceAsync(ITimeTracker <CompositionLoadMetadata> timer, HashSet <Assembly> mefAssemblies)
        {
            var metadata  = timer.Metadata;
            var fullTimer = System.Diagnostics.Stopwatch.StartNew();
            var stepTimer = System.Diagnostics.Stopwatch.StartNew();

            var caching = new Caching(mefAssemblies, new IdeRuntimeCompositionExceptionHandler());

            // Try to use cached MEF data
            using (timer) {
                var canUse = metadata.ValidCache = caching.CanUse();
                if (canUse)
                {
                    LoggingService.LogInfo("Creating MEF composition from cache");
                    RuntimeComposition = await TryCreateRuntimeCompositionFromCache(caching);
                }
                metadata.Timings ["LoadFromCache"] = stepTimer.ElapsedMilliseconds;
                stepTimer.Restart();

                // Otherwise fallback to runtime discovery.
                if (RuntimeComposition == null)
                {
                    LoggingService.LogInfo("Creating MEF composition from runtime");
                    var(runtimeComposition, catalog) = await CreateRuntimeCompositionFromDiscovery(caching, timer);

                    RuntimeComposition = runtimeComposition;

                    CachedComposition cacheManager = new CachedComposition();
                    caching.Write(RuntimeComposition, catalog, cacheManager).Ignore();
                }
                metadata.Timings ["LoadRuntimeComposition"] = stepTimer.ElapsedMilliseconds;
                stepTimer.Restart();

                ExportProviderFactory = RuntimeComposition.CreateExportProviderFactory();
                ExportProvider        = ExportProviderFactory.CreateExportProvider();
                HostServices          = Microsoft.VisualStudio.LanguageServices.VisualStudioMefHostServices.Create(ExportProvider);

                metadata.Timings ["CreateServices"] = stepTimer.ElapsedMilliseconds;
                metadata.Duration = fullTimer.ElapsedMilliseconds;
            }
        }
コード例 #15
0
            internal void Compose(Stream cachedCatalog)
            {
                Requires.NotNull(cachedCatalog, nameof(cachedCatalog));

                Stream cachedCatalogLocal = CopyStream(cachedCatalog);

                // Deserialize the catalog to verify that it doesn't load any assemblies.
                var catalogManager = new CachedCatalog();

                this.catalog = catalogManager.LoadAsync(cachedCatalogLocal, TestUtilities.Resolver).Result;

                var configuration = CompositionConfiguration.Create(this.catalog);

                var cacheManager = new CachedComposition();
                var ms           = new MemoryStream();

                cacheManager.SaveAsync(configuration, ms).GetAwaiter().GetResult();
                ms.Position = 0;

                var containerFactory = cacheManager.LoadExportProviderFactoryAsync(ms, TestUtilities.Resolver).GetAwaiter().GetResult();

                this.container = containerFactory.CreateExportProvider();
            }
コード例 #16
0
            internal Task Write(RuntimeComposition runtimeComposition, ComposableCatalog catalog, CachedComposition cacheManager)
            {
                return(Runtime.RunInMainThread(async() => {
                    IdeApp.Exiting += IdeApp_Exiting;

                    saveTask = Task.Run(async() => {
                        try {
                            await WriteMefCache(runtimeComposition, catalog, cacheManager);
                        } catch (Exception ex) {
                            exceptionHandler.HandleException("Failed to write MEF cache", ex);
                        }
                    });
                    await saveTask;

                    IdeApp.Exiting -= IdeApp_Exiting;
                    saveTask = null;
                }));
            }
コード例 #17
0
        public override bool Execute()
        {
            if (Environment.GetEnvironmentVariable("CreateCompositionTaskDebug") == "1")
            {
                Debugger.Launch();
            }

            this.catalogAssemblyPaths.AddRange(this.CatalogAssemblies.Select(this.GetMEFAssemblyFullPath));

            AppDomain.CurrentDomain.AssemblyResolve += this.CurrentDomain_AssemblyResolve;
            try
            {
                var loadableAssemblies = this.catalogAssemblyPaths
                                         .Concat(this.ReferenceAssemblies.Select(i => i.GetMetadata("FullPath")) ?? Enumerable.Empty <string>());
                var resolver  = new Resolver(new AssemblyLoader(loadableAssemblies));
                var discovery = PartDiscovery.Combine(
                    new AttributedPartDiscoveryV1(resolver),
                    new AttributedPartDiscovery(resolver, isNonPublicSupported: true));

                this.CancellationToken.ThrowIfCancellationRequested();

                var parts   = discovery.CreatePartsAsync(this.catalogAssemblyPaths).GetAwaiter().GetResult();
                var catalog = ComposableCatalog.Create(resolver)
                              .AddParts(parts);

                this.LogLines(this.GetLogFilePath("CatalogAssemblies"), this.GetCatalogAssembliesLines(catalog), this.CancellationToken);

                string catalogErrorFilePath = this.GetLogFilePath("CatalogErrors");
                if (catalog.DiscoveredParts.DiscoveryErrors.IsEmpty)
                {
                    File.Delete(catalogErrorFilePath);
                }
                else
                {
                    this.LogLines(catalogErrorFilePath, GetCatalogErrorLines(catalog), this.CancellationToken);
                    foreach (var error in catalog.DiscoveredParts.DiscoveryErrors)
                    {
                        string message = error.GetUserMessage();
                        if (this.ContinueOnDiscoveryErrors)
                        {
                            this.LogWarning(DiscoveryErrorCode, message);
                        }
                        else
                        {
                            this.Log.LogError(null, DiscoveryErrorCode, null, null, 0, 0, 0, 0, message);
                        }
                    }

                    if (!this.ContinueOnDiscoveryErrors)
                    {
                        return(false);
                    }
                }

                this.CancellationToken.ThrowIfCancellationRequested();
                var configuration = CompositionConfiguration.Create(catalog);

                if (!string.IsNullOrEmpty(this.DgmlOutputPath))
                {
                    configuration.CreateDgml().Save(this.DgmlOutputPath);
                    this.writtenFiles.Add(this.DgmlOutputPath);
                }

                this.CancellationToken.ThrowIfCancellationRequested();
                string compositionLogPath = this.GetLogFilePath("CompositionErrors");
                if (configuration.CompositionErrors.IsEmpty)
                {
                    File.Delete(compositionLogPath);
                }
                else
                {
                    this.LogLines(compositionLogPath, GetCompositionErrorLines(configuration), this.CancellationToken);
                    foreach (var error in configuration.CompositionErrors.Peek())
                    {
                        if (this.ContinueOnCompositionErrors)
                        {
                            this.LogWarning(CompositionErrorCode, error.Message);
                        }
                        else
                        {
                            this.Log.LogError(null, CompositionErrorCode, null, null, 0, 0, 0, 0, error.Message);
                        }
                    }

                    if (!this.ContinueOnCompositionErrors)
                    {
                        return(false);
                    }
                }

                this.CancellationToken.ThrowIfCancellationRequested();

                string cachePath = Path.GetFullPath(this.CompositionCacheFile);
                this.Log.LogMessage("Producing IoC container \"{0}\"", cachePath);
                using (var cacheStream = File.Open(cachePath, FileMode.Create))
                {
                    this.CancellationToken.ThrowIfCancellationRequested();
                    var runtime = RuntimeComposition.CreateRuntimeComposition(configuration);
                    this.CancellationToken.ThrowIfCancellationRequested();
                    var runtimeCache = new CachedComposition();
                    runtimeCache.SaveAsync(runtime, cacheStream, this.CancellationToken).GetAwaiter().GetResult();
                }

                this.writtenFiles.Add(cachePath);

                return(!this.Log.HasLoggedErrors);
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= this.CurrentDomain_AssemblyResolve;
                this.FileWrites = this.writtenFiles.Select(f => new TaskItem(f)).ToArray();
            }
        }
コード例 #18
0
            internal Task Write(RuntimeComposition runtimeComposition, ComposableCatalog catalog, CachedComposition cacheManager)
            {
                return(Runtime.RunInMainThread(async() => {
                    IdeApp.Exiting += IdeApp_Exiting;

                    saveTask = Task.Run(async() => {
                        try {
                            cachingFaultInjector?.FaultWritingComposition();
                            await WriteMefCache(runtimeComposition, catalog, cacheManager);
                        } catch (Exception ex) {
                            DeleteFiles();

                            Runtime.RunInMainThread(() => {
                                exceptionHandler.HandleException("Failed to write MEF cache", ex);
                            }).Ignore();
                        }
                    });
                    await saveTask;

                    IdeApp.Exiting -= IdeApp_Exiting;
                    saveTask = Task.CompletedTask;
                }));
            }