public void VimWpfDoesntHoldBuffer() { var list = EditorUtil.GetEditorCatalog(); list.Add(new TypeCatalog(typeof(Vim.UnitTest.Exports.VimHost))); list.Add(new AssemblyCatalog(typeof(Vim.IVim).Assembly)); list.Add(new AssemblyCatalog(typeof(Vim.UI.Wpf.KeyProcessor).Assembly)); var catalog = new AggregateCatalog(list.ToArray()); var container = new CompositionContainer(catalog); var factory = container.GetExport <ITextEditorFactoryService>().Value; var textView = factory.CreateTextView(); // Verify we actually created the IVimBuffer instance var vim = container.GetExport <IVim>().Value; var vimBuffer = vim.GetOrCreateBuffer(textView); Assert.IsNotNull(vimBuffer); var weakVimBuffer = new WeakReference(vimBuffer); var weakTextView = new WeakReference(textView); // Clean up textView.Close(); textView = null; vimBuffer.Close(); vimBuffer = null; RunGarbageCollector(); Assert.IsNull(weakVimBuffer.Target); Assert.IsNull(weakTextView.Target); }
private void ValidMetadataDiscoveredByCatalog(CompositionContainer container) { var export1 = container.GetExport <MyExporterWithValidMetadata, IDictionary <string, object> >(); var metadataFoo = export1.Metadata["foo"] as IList <string>; Assert.AreEqual(2, metadataFoo.Count(), "There are should be two items in the metadata foo's collection"); Assert.IsTrue(metadataFoo.Contains("bar1"), "The metadata collection should include value 'bar1'"); Assert.IsTrue(metadataFoo.Contains("bar2"), "The metadata collection should include value 'bar2'"); Assert.AreEqual("world", export1.Metadata["hello"], "The single item metadata should also be present"); Assert.AreEqual("GoodOneValue2", export1.Metadata["GoodOne2"], "The metadata supplied by strong attribute should also be present"); var metadataAcme = export1.Metadata["acme"] as IList <object>; Assert.AreEqual(2, metadataAcme.Count(), "There are should be two items in the metadata acme's collection"); Assert.IsTrue(metadataAcme.Contains("acmebar"), "The metadata collection should include value 'bar'"); Assert.IsTrue(metadataAcme.Contains(2.0), "The metadata collection should include value 2"); var export2 = container.GetExport <Func <double>, IDictionary <string, object> >("ContractForValidMetadata"); var metadataBar = export2.Metadata["bar"] as IList <string>; Assert.AreEqual(2, metadataBar.Count(), "There are should be two items in the metadata foo's collection"); Assert.IsTrue(metadataBar.Contains("foo1"), "The metadata collection should include value 'foo1'"); Assert.IsTrue(metadataBar.Contains("foo2"), "The metadata collection should include value 'foo2'"); Assert.AreEqual("hello", export2.Metadata["world"], "The single item metadata should also be present"); Assert.AreEqual("GoodOneValue2", export2.Metadata["GoodOne2"], "The metadata supplied by strong attribute should also be present"); var metadataStuff = export2.Metadata["stuff"] as IList <object>; Assert.AreEqual(2, metadataAcme.Count(), "There are should be two items in the metadata acme's collection"); Assert.IsTrue(metadataStuff.Contains("acmebar"), "The metadata collection should include value 'acmebar'"); Assert.IsTrue(metadataStuff.Contains(2.0), "The metadata collection should include value 2"); }
protected override void OnStartup(StartupEventArgs e) { RegisterLoadedHandler(); base.OnStartup(e); // bootstrap MEF composition var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); Container = new CompositionContainer(catalog); // retrieve the MefContentLoader export and assign to global resources (so {DynamicResource MefContentLoader} can be resolved) var contentLoader = Container.GetExport <MefContentLoader>().Value; Resources.Add("MefContentLoader", contentLoader); // same for MefLinkNavigator var navigator = Container.GetExport <MefLinkNavigator>().Value; Resources.Add("MefLinkNavigator", navigator); _viewModelLoader = Container.GetExport <MefViewModelLoader>().Value; DebuggerSession.Instance.OnDetach += OnDetach; AppearanceManager.Current.AccentColor = Color.FromRgb(0xf0, 0x96, 0x09); }
private IVimBuffer CreateVimBuffer() { var list = EditorUtil.GetEditorCatalog(); list.Add(new AssemblyCatalog(typeof(Vim.IVim).Assembly)); list.Add(new AssemblyCatalog(typeof(Vim.UI.Wpf.KeyProcessor).Assembly)); list.Add(new AssemblyCatalog(typeof(VsVim.VsCommandTarget).Assembly)); list.Add(new TypeCatalog( typeof(VsVim.UnitTest.MemoryLeakTest.ServiceProvider), typeof(VsVim.UnitTest.MemoryLeakTest.VsEditorAdaptersFactoryService), typeof(VsVim.UnitTest.MemoryLeakTest.ErrorHandler))); var catalog = new AggregateCatalog(list.ToArray()); var container = new CompositionContainer(catalog); var factory = container.GetExport <ITextEditorFactoryService>().Value; var textView = factory.CreateTextView(); // Verify we actually created the IVimBuffer instance _vim = container.GetExport <IVim>().Value; var vimBuffer = _vim.GetOrCreateBuffer(textView); Assert.IsNotNull(vimBuffer); // Do one round of DoEvents since several services queue up actions to // take immediately after the IVimBuffer is created for (var i = 0; i < 10; i++) { Dispatcher.CurrentDispatcher.DoEvents(); } return(vimBuffer); }
public void Mef_can_use_container_hierarchy_to_have_scoped_composable_parts() { var rootContainer = Mef; var rootCatalog = rootContainer.Catalog; var nonSharedPartsCatalog = new FilteredCatalog(rootCatalog, def => IsNonSharedOrAny(def)); IDisposableScopedService scoped1, scoped2; IDisposableSingletonService singleton1, singleton2; using (var scope1 = new CompositionContainer(nonSharedPartsCatalog, rootContainer)) { scoped1 = scope1.GetExport <IDisposableScopedService>().Value; singleton1 = scope1.GetExport <IDisposableSingletonService>().Value; Assert.IsFalse(scoped1.IsDisposed); Assert.IsFalse(singleton1.IsDisposed); using (var scope2 = new CompositionContainer(nonSharedPartsCatalog, rootContainer)) { scoped2 = scope2.GetExport <IDisposableScopedService>().Value; singleton2 = scope2.GetExport <IDisposableSingletonService>().Value; Assert.AreNotSame(scoped1, scoped2); Assert.AreSame(singleton1, singleton2); } Assert.IsTrue(scoped2.IsDisposed); Assert.IsFalse(scoped1.IsDisposed); Assert.IsFalse(singleton2.IsDisposed); } Assert.IsTrue(scoped1.IsDisposed); Assert.IsFalse(singleton1.IsDisposed); rootContainer.Dispose(); Assert.IsTrue(singleton1.IsDisposed); }
private void ValidMetadataDiscoveredByCatalog(CompositionContainer container) { var export1 = container.GetExport <MyExporterWithValidMetadata, IDictionary <string, object> >(); var metadataFoo = export1.Metadata["foo"] as IList <string>; Assert.Equal(2, metadataFoo.Count()); Assert.True(metadataFoo.Contains("bar1"), "The metadata collection should include value 'bar1'"); Assert.True(metadataFoo.Contains("bar2"), "The metadata collection should include value 'bar2'"); Assert.Equal("world", export1.Metadata["hello"]); Assert.Equal("GoodOneValue2", export1.Metadata["GoodOne2"]); var metadataAcme = export1.Metadata["acme"] as IList <object>; Assert.Equal(2, metadataAcme.Count()); Assert.True(metadataAcme.Contains("acmebar"), "The metadata collection should include value 'bar'"); Assert.True(metadataAcme.Contains(2.0), "The metadata collection should include value 2"); var export2 = container.GetExport <Func <double>, IDictionary <string, object> >("ContractForValidMetadata"); var metadataBar = export2.Metadata["bar"] as IList <string>; Assert.Equal(2, metadataBar.Count()); Assert.True(metadataBar.Contains("foo1"), "The metadata collection should include value 'foo1'"); Assert.True(metadataBar.Contains("foo2"), "The metadata collection should include value 'foo2'"); Assert.Equal("hello", export2.Metadata["world"]); Assert.Equal("GoodOneValue2", export2.Metadata["GoodOne2"]); var metadataStuff = export2.Metadata["stuff"] as IList <object>; Assert.Equal(2, metadataAcme.Count()); Assert.True(metadataStuff.Contains("acmebar"), "The metadata collection should include value 'acmebar'"); Assert.True(metadataStuff.Contains(2.0), "The metadata collection should include value 2"); }
/// <summary> /// Registers component implementing interface I. Component instance is provided by MEF container. /// </summary> static void RegisterComponent <I>(this IComponentCatalog host, ComposablePartCatalog childCatalog, CompositionContainer parentContainer, string contractName, ActivationType activationType) { var uniqueName = contractName ?? typeof(I).FullName; // Singleton component instance is created in the parent container if (activationType == ActivationType.Singleton) { host.RegisterComponent <I> ( uniqueName, delegate // lazy-initialized singleton factory { var component = contractName != null ? parentContainer.GetExport <I>(contractName).Value : parentContainer.GetExport <I>().Value; return(component); }, ActivationType.Singleton, delegate(object component) // empty cleanup handler { // do not clean up component instance // even if it implements IDisposable } ); return; } // Dictionary: component -> owning container var containers = new ConcurrentDictionary <object, CompositionContainer>(); // SingleCall component instance is created inside the child container host.RegisterComponent <I> ( uniqueName, delegate // factory method { // create child container for early component disposal var childContainer = new CompositionContainer(childCatalog, parentContainer); var component = contractName != null ? childContainer.GetExport <I>(contractName).Value : childContainer.GetExport <I>().Value; containers[component] = childContainer; return(component); }, ActivationType.SingleCall, delegate(object component) // cleanup delegate { CompositionContainer childContainer; // free child container and release non-shared MEF component if (containers.TryRemove(component, out childContainer)) { childContainer.Dispose(); } } ); }
public void Convert(string deviceDefSchemaFileName, string deviceGroupConfigFileName) { var deviceDefSchemaRepository = _container.GetExport <IDeviceDefSchemaRepository>("Xaml").Value; var deviceDefSchema = deviceDefSchemaRepository.Load(deviceDefSchemaFileName); GenerateDeviceConfigs(deviceDefSchema); }
public T GetInstance <T>() { var export = _container.GetExport <T>(); if (export == null) { return(default(T)); } return(export.Value); }
/// <summary> /// 生成指定類型的實例 /// </summary> /// <typeparam name="T">類型參數</typeparam> /// <returns>指定類型的實例</returns> public Lazy <T> GetExport <T>() { try { return(_container.GetExport <T>()); } catch (Exception ex) { throw CreateComposerException(typeof(T), null, ex); } }
/// <summary> /// Retourne l'instance du viewModel demandée /// </summary> /// <typeparam name="TViewModel">type de viewModel demandé</typeparam> /// <returns>l'instance du viewModel demandée</returns> public TViewModel GetViewModel <TViewModel>() where TViewModel : IViewModel { // Récupère l'export depuis MEF var export = _container.GetExport <TViewModel, IExport>(); // Récupère l'instance du view model var result = export.Value; // Retourne une instance du type de viewModel demandé return(result); }
internal InteractiveWindowTestHost() { _exportProvider = new CompositionContainer( s_lazyCatalog.Value, CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); var contentTypeRegistryService = _exportProvider.GetExport <IContentTypeRegistryService>().Value; Evaluator = new TestInteractiveEvaluator(); Window = _exportProvider.GetExport <IInteractiveWindowFactoryService>().Value.CreateWindow(Evaluator); Window.InitializeAsync().Wait(); }
internal InteractiveWindowTestHost(Action <InteractiveWindow.State> stateChangedHandler = null) { ExportProvider = new CompositionContainer( _lazyCatalog.Value, CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); var contentTypeRegistryService = ExportProvider.GetExport <IContentTypeRegistryService>().Value; Evaluator = new TestInteractiveEngine(contentTypeRegistryService); Window = ExportProvider.GetExport <IInteractiveWindowFactoryService>().Value.CreateWindow(Evaluator); ((InteractiveWindow)Window).StateChanged += stateChangedHandler; Window.InitializeAsync().Wait(); }
public static void Run(IGlobalContext rightNowGlobalContext) { var catalog = new AssemblyCatalog(typeof(CtiServiceSwitch).Assembly); _container = new CompositionContainer(catalog); _container.ComposeParts(); _container.ComposeExportedValue(rightNowGlobalContext); _container.GetExport <CtiServiceSwitch>().Value._messagingHandler.Initialize(); _container.GetExport <IncidentProcessor>().Value.Initialize(); // _container.GetExport<TwilioVoiceProcessor>().Value.Initialize(); }
internal InteractiveWindowTestHost(Action <InteractiveWindow.State> stateChangedHandler = null) { SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); _exportProvider = new CompositionContainer( _lazyCatalog.Value, CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); var contentTypeRegistryService = _exportProvider.GetExport <IContentTypeRegistryService>().Value; _window = _exportProvider.GetExport <IInteractiveWindowFactoryService>().Value.CreateWindow(new TestInteractiveEngine(contentTypeRegistryService)); ((InteractiveWindow)_window).StateChanged += stateChangedHandler; _window.InitializeAsync().PumpingWait(); }
public MainWindow() { InitializeComponent(); EnvironmentsToolWindow.ViewCreated += EnvironmentsToolWindow_ViewCreated; _container = new CompositionContainer(new AggregateCatalog( new AssemblyCatalog(typeof(IInterpreterRegistryService).Assembly), new AssemblyCatalog(typeof(IInterpreterOptionsService).Assembly) )); EnvironmentsToolWindow.Interpreters = _container.GetExport <IInterpreterRegistryService>().Value; EnvironmentsToolWindow.Service = _container.GetExport <IInterpreterOptionsService>().Value; }
private static T GetValueFromCatalog <T>(AggregateCatalog catalog, out CompositionContainer container, string exportName = null) { container = new CompositionContainer(catalog); var export = exportName == null?container.GetExport <T>() : container.GetExport <T>(exportName); if (export == null) { throw new ApplicationException($"MEF: Implementation for type {typeof(T).Name} not found. " + $"Full Path(s)={string.Join(",", catalog.Catalogs.Where(x => x is DirectoryCatalog).Cast<DirectoryCatalog>().Select(x => x.FullPath))}; exportName={exportName}"); } return(export.Value); //the container will be disposed if only if T or the realization of T does not implement IDisposable }
static void Main(string[] args) { var builder = new RegistrationBuilder(); builder .ForTypesDerivedFrom <IPlugin>() .Export <IPlugin>(); builder .ForType <PluginStore>() .Export() .ImportProperties( propertyFilter => true, (propertyInfo, importBuilder) => { importBuilder.AsMany(); } ); var catalog = new AssemblyCatalog(typeof(PluginStore).Assembly, builder); using (var container = new CompositionContainer(catalog)) { var pluginManager = container.GetExport <PluginStore>().Value; foreach (var plugn in pluginManager.Plugins) { Console.WriteLine("{0}, {1}", plugn.Metadata.Name, plugn.Metadata.Version); plugn.Value.Run(); } } }
public static ServerEntry LoadServer(string path) { try { // Create a server entry for the server. var serverEntry = new ServerEntry(); // Set the data. serverEntry.ServerName = Path.GetFileNameWithoutExtension(path); serverEntry.ServerPath = path; // Create an assembly catalog for the assembly and a container from it. var catalog = new AssemblyCatalog(Path.GetFullPath(path)); var container = new CompositionContainer(catalog); // Get the exported server. var server = container.GetExport <ISharpShellServer>().Value; serverEntry.ServerType = server.ServerType; serverEntry.ClassId = server.GetType().GUID; serverEntry.Server = server; return(serverEntry); } catch (Exception) { // It's almost certainly not a COM server. MessageBox.Show("The file '" + Path.GetFileName(path) + "' is not a SharpShell Server.", "Warning"); return(null); } }
/// <summary> /// 返回具有指定的协定名称的导出 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="searchPattern">搜索字符串</param> /// <param name="contractName">协定名称</param> /// <returns></returns> public static T GetExport <T>(string searchPattern, string contractName) { var dirCatalog = new DirectoryCatalog(".", searchPattern); var container = new CompositionContainer(dirCatalog); return(container.GetExport <T>(contractName).Value); }
public void GetExportManualDisposeThenRecompose_NonSharedDisposableRecomposablePart_ShouldThrowComposition() { var catalog = new TypeCatalog(typeof(NonSharedPartDisposableRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); var export = container.GetExport <NonSharedPartDisposableRecomposable>(); var exportedValue = export.Value; Assert.AreEqual(21, exportedValue.Value); exportedValue.Dispose(); // Recompose should cause a ObjectDisposedException. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); CompositionAssert.ThrowsError( ErrorId.ImportEngine_PartCannotActivate, // Cannot activate part because ErrorId.ReflectionModel_ImportThrewException, // Import threw an exception RetryMode.DoNotRetry, () => { container.Compose(batch); }); }
public void GetReleaseExport_NonSharedPart_ShouldNotRecomposeAfterRelease() { var catalog = new TypeCatalog(typeof(NonSharedPartRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); var export = container.GetExport <NonSharedPartRecomposable>(); var exportedValue = export.Value; Assert.AreEqual(21, exportedValue.Value); container.ReleaseExport(export); // Recompose just to ensure we don't blow up, even though we don't expect anything to happen. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); Assert.AreEqual(21, exportedValue.Value, "Value should not be recomposed after ReleaseExport is called on it."); }
[ActiveIssue("https://github.com/dotnet/corefx/issues/25498", TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void GetValuesByType() { var cat = CatalogFactory.CreateDefaultAttributed(); var container = new CompositionContainer(cat); string itestName = AttributedModelServices.GetContractName(typeof(ITest)); var e1 = container.GetExportedValues <ITest>(); var e2 = container.GetExports <ITest, object>(itestName); Assert.IsType <T1>(e1.First()); Assert.IsType <T2>(e1.Skip(1).First()); Assert.IsType <T1>(e2.First().Value); Assert.IsType <T2>(e2.Skip(1).First().Value); CompositionContainer childContainer = new CompositionContainer(container); CompositionBatch batch = new CompositionBatch(); batch.AddPart(new T1()); container.Compose(batch); var t1 = childContainer.GetExportedValue <ITest>(); var t2 = childContainer.GetExport <ITest, object>(itestName); Assert.IsType <T1>(t1); Assert.IsType <T1>(t2.Value); }
public void LoadPlugins(IPluginHost host) { var dir = _options.PluginDir; var pluginDirs = Directory.GetDirectories(dir); var list = new List <DirectoryCatalog>(); var def = new ImportDefinition(d => d.ContractName == typeof(IPlugin).FullName, "", ImportCardinality.ExactlyOne, false, false); var plugins = new List <IPlugin>(); foreach (var pluginDir in pluginDirs) { var files = Directory.GetFiles(pluginDir).Where(s => s.EndsWith("Plugin.dll"));//ファイル名がPlugin.dllで終わるアセンブリだけ探す foreach (var file in files) { try { var catalog = new AssemblyCatalog(file); var con = new CompositionContainer(catalog); var plugin = con.GetExport <IPlugin>().Value; plugins.Add(plugin); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } list.Add(new DirectoryCatalog(pluginDir)); } _plugins = plugins; foreach (var plugin in _plugins) { plugin.Host = host; PluginAdded?.Invoke(this, plugin); } }
static void Main(string[] args) { //var tranformer = new MovieTransformer(new InMemoryMovieSource(), new CsvMoviePersistor()); //tranformer.Transform(); var assemblyCatalog = new AssemblyCatalog(typeof(Program).Assembly); var directoryCatalog = new DirectoryCatalog("plugins"); var aggregateCatalog = new AggregateCatalog(assemblyCatalog, directoryCatalog); var container = new CompositionContainer(aggregateCatalog); var c = container.GetExport <IMovieTransformer>(); var movieTransformer = container.GetExportedValue <IMovieTransformer>(); movieTransformer.Transform(); Console.WriteLine("Done"); var lazyEmp = new MyLazy <Employee>(GetEmployeeFromDatabase); Console.WriteLine(lazyEmp.HasValue); Console.WriteLine(DateTime.Now); var emp = lazyEmp.Value; Console.WriteLine(DateTime.Now); Console.WriteLine(lazyEmp.HasValue); Console.WriteLine(DateTime.Now); emp = lazyEmp.Value; Console.WriteLine(DateTime.Now); Console.ReadLine(); }
public InteractiveWindowTestHost() { SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); var types = new[] { typeof(TestInteractiveEngine), typeof(InteractiveWindow) }.Concat(GetVisualStudioTypes()); _exportProvider = new CompositionContainer( new AggregateCatalog(types.Select(t => new AssemblyCatalog(t.Assembly))), CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); var contentTypeRegistryService = _exportProvider.GetExport <IContentTypeRegistryService>().Value; _window = _exportProvider.GetExport <IInteractiveWindowFactoryService>().Value.CreateWindow(new TestInteractiveEngine(contentTypeRegistryService)); _window.InitializeAsync().PumpingWait(); }
static void Main() { var engine = new GUILayer.EngineDevice(); GC.KeepAlive(engine); var catalog = new TypeCatalog( typeof(ShaderPatcherLayer.Manager), typeof(ShaderFragmentArchive.Archive), typeof(NodeEditorCore.ShaderFragmentArchiveModel), typeof(NodeEditorCore.ModelConversion), typeof(NodeEditorCore.ShaderFragmentNodeCreator), typeof(NodeEditorCore.DiagramDocument), typeof(ExampleForm) ); using (var container = new CompositionContainer(catalog)) { container.ComposeExportedValue <ExportProvider>(container); container.ComposeExportedValue <CompositionContainer>(container); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(container.GetExport <ExampleForm>().Value); } engine.Dispose(); }
public void Start() { var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(typeof(SearchDemo).Assembly)); var container = new CompositionContainer(catalog); container.ComposeParts(); try { var component = container.GetExport <ITestComponent>(); if (component != null) { Console.WriteLine(component.Value.Message); } } catch (Exception exp) { //Why does our call to 'GetExport' throw an exception? //Search for the string "Test" on the container variable //You'll find 3 instances in the Catalog. //Then search for ITestComponent. //You'll need to click "Search Deeper" to expand the search. //Another way to do this is to view "container.Catalog.Parts", right click it, //select 'Edit Filter' and enter the following predicate: // [obj].Exports(typoef(ITestComponent)) MessageBox.Show(exp.Message, "Exception caught!"); } }
public void GetValuesByType() { var cat = CatalogFactory.CreateDefaultAttributed(); var container = new CompositionContainer(cat); string itestName = AttributedModelServices.GetContractName(typeof(ITest)); var e1 = container.GetExportedValues <ITest>(); var e2 = container.GetExports <ITest, object>(itestName); Assert.IsInstanceOfType(e1.First(), typeof(T1), "First should be T1"); Assert.IsInstanceOfType(e1.Skip(1).First(), typeof(T2), "Second should be T2"); Assert.IsInstanceOfType(e2.First().Value, typeof(T1), "First should be T1"); Assert.IsInstanceOfType(e2.Skip(1).First().Value, typeof(T2), "Second should be T2"); CompositionContainer childContainer = new CompositionContainer(container); CompositionBatch batch = new CompositionBatch(); batch.AddPart(new T1()); container.Compose(batch); var t1 = childContainer.GetExportedValue <ITest>(); var t2 = childContainer.GetExport <ITest, object>(itestName); Assert.IsInstanceOfType(t1, typeof(T1), "First (resolved) should be T1"); Assert.IsInstanceOfType(t2.Value, typeof(T1), "First (resolved) should be T1"); }
public App() { var cmdArgs = Environment.GetCommandLineArgs().Skip(1); App.CommandLineArguments = new CommandLineArguments(cmdArgs); if (App.CommandLineArguments.SingleInstance ?? true) { cmdArgs = cmdArgs.Select(FullyQualifyPath); string message = string.Join(Environment.NewLine, cmdArgs); if (SendToPreviousInstance("ILSpy:\r\n" + message, !App.CommandLineArguments.NoActivate)) { Environment.Exit(0); } } InitializeComponent(); var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly)); // Don't use DirectoryCatalog, that causes problems if the plugins are from the Internet zone // see http://stackoverflow.com/questions/8063841/mef-loading-plugins-from-a-network-shared-folder string appPath = Path.GetDirectoryName(typeof(App).Module.FullyQualifiedName); foreach (string plugin in Directory.GetFiles(appPath, "*.Plugin.dll")) { string shortName = Path.GetFileNameWithoutExtension(plugin); try { var asm = Assembly.Load(shortName); asm.GetTypes(); catalog.Catalogs.Add(new AssemblyCatalog(asm)); } catch (Exception ex) { // Cannot show MessageBox here, because WPF would crash with a XamlParseException // Remember and show exceptions in text output, once MainWindow is properly initialized StartupExceptions.Add(new ExceptionData { Exception = ex, PluginName = shortName }); } } compositionContainer = new CompositionContainer(catalog); Languages.Initialize(compositionContainer); if (!System.Diagnostics.Debugger.IsAttached) { AppDomain.CurrentDomain.UnhandledException += ShowErrorBox; Dispatcher.CurrentDispatcher.UnhandledException += Dispatcher_UnhandledException; } EventManager.RegisterClassHandler(typeof(Window), Hyperlink.RequestNavigateEvent, new RequestNavigateEventHandler(Window_RequestNavigate)); try { DebuggerService.SetDebugger(compositionContainer.GetExport <IDebugger>()); } catch { // unable to find a IDebugger } }