private object GetExport(Type type, string name) { object exportedObject = null; try { exportedObject = _container.GetExport(type, name); } catch (CompositionFailedException ex) { Logger.LogWarning($"Can't import: {name}, {ex}"); } return(exportedObject); }
public void WithPart_Convention_Success() { var conventions = new ConventionBuilder(); conventions.ForType <ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); Assert.Same(configuration, configuration.WithPart(typeof(ExportedProperty), conventions)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("A", container.GetExport <string>()); }
private OmnisharpWorkspace CreateWorkspace( CompositionHost compositionHost, Dictionary <string, string> sourceFiles) { compositionHost = compositionHost ?? CreatePluginHost(typeof(CodeCheckService).GetTypeInfo().Assembly); var workspace = compositionHost.GetExport <OmnisharpWorkspace>(); AddProjectToWorkspace(workspace, "project.json", new[] { "dnx451", "dnxcore50" }, sourceFiles); // Logic is copied from TestHelper, no idea what's waiting for. Thread.Sleep(50); return(workspace); }
private Task Initialize(Extensions.LanguageServer.Server.ILanguageServer server, InitializeParams initializeParams) { CreateCompositionHost(initializeParams); // TODO: Make it easier to resolve handlers from MEF (without having to add more attributes to the services if we can help it) var workspace = _compositionHost.GetExport <OmniSharpWorkspace>(); _compositionHost.GetExport <DiagnosticEventForwarder>().IsEnabled = true; foreach (var handler in TextDocumentSyncHandler.Enumerate(_handlers, workspace) .Concat(DefinitionHandler.Enumerate(_handlers)) .Concat(HoverHandler.Enumerate(_handlers)) .Concat(CompletionHandler.Enumerate(_handlers)) .Concat(SignatureHelpHandler.Enumerate(_handlers)) .Concat(RenameHandler.Enumerate(_handlers)) .Concat(DocumentSymbolHandler.Enumerate(_handlers)) .Concat(ReferencesHandler.Enumerate(_handlers)) .Concat(CodeLensHandler.Enumerate(_handlers))) { server.AddHandlers(handler); } return(Task.CompletedTask); }
public MefDependencyResolver(CompositionHost rootCompositionScope) : base(new Export <CompositionContext>(rootCompositionScope, rootCompositionScope.Dispose)) { if (rootCompositionScope == null) { throw new ArgumentNullException("rootCompositionScope"); } var factoryContract = new CompositionContract(typeof(ExportFactory <CompositionContext>), null, new Dictionary <string, object> { { "SharingBoundaryNames", new[] { "HttpRequest" } } }); _requestScopeFactory = (ExportFactory <CompositionContext>)rootCompositionScope.GetExport(factoryContract); }
public void WithDefaultConventions_IEnumerablePartsWithNoMatchingConvention_Success() { var conventions = new ConventionBuilder(); conventions.ForType <ExportedProperty>().ExportProperty(b => b.Property); var configuration = new ContainerConfiguration(); configuration.WithParts((IEnumerable <Type>) new Type[] { typeof(ExportedProperty) }); Assert.Same(configuration, configuration.WithDefaultConventions(conventions)); CompositionHost container = configuration.CreateContainer(); Assert.Equal("A", container.GetExport <string>()); }
public StandaloneDependencyResolver(CompositionHost rootCompositionScope) : base(new Export <CompositionContext>(rootCompositionScope, rootCompositionScope.Dispose)) { if (rootCompositionScope == null) { throw new ArgumentNullException(nameof(rootCompositionScope)); } var metadataConstraints = new Dictionary <string, object> { { "SharingBoundaryNames", new[] { "HttpRequest" } } }; var factoryContract = new CompositionContract(typeof(ExportFactory <CompositionContext>), contractName: null, metadataConstraints: metadataConstraints); this.requestScopeFactory = (ExportFactory <CompositionContext>)rootCompositionScope.GetExport(factoryContract); }
private static void Main(string[] args) { Console.WriteLine("开始......"); string ProjectPath = ConfigurationManager.AppSettings.Get("ProjectPath"); Project Pj; List <Conmgr> Conmgrs; List <Package> Packages; Dictionary <int, EzOleDbConnectionManager> CMS; using (AutossisEntities db = new AutossisEntities()) { Pj = db.Project.Where(p => p.ProjectName == projectName).First(); Conmgrs = db.Conmgr.Where(p => p.ProjectId == Pj.ProjectId).ToList(); Packages = db.Package.Where(p => p.ProjectId == Pj.ProjectId).ToList(); CMS = getOledbConnectionManagers(Conmgrs); } ConventionBuilder conventions = new ConventionBuilder(); conventions .ForTypesDerivedFrom <ICreatePackage>() .Export <ICreatePackage>() .Shared(); Assembly[] assemblies = new[] { typeof(Program).GetTypeInfo().Assembly }; ContainerConfiguration configuration = new ContainerConfiguration() .WithAssemblies(assemblies, conventions); ICreatePackage Cp; using (CompositionHost container = configuration.CreateContainer()) { Cp = container.GetExport <ICreatePackage>(ConfigurationManager.AppSettings.Get("ProjectType")); Cp.ezOleDbConnectionManagers = CMS; } foreach (Package package in Packages) { ez.AddPackage(Cp.Create(package)); Console.WriteLine(package.PackageName + " 生成成功。"); } JobControl(Pj, null); ez.SaveTo(ProjectPath + Pj.ProjectName + ".ispac"); Console.WriteLine("全部成功!"); Console.ReadKey(); }
public void WithProvider_ValidProvider_RegistersProvider() { var configuration = new ContainerConfiguration(); var provider = new ExportProvider { Result = 10 }; Assert.Same(configuration, configuration.WithProvider(provider)); CompositionHost container = configuration.CreateContainer(); Assert.Equal(0, provider.CalledGetExportDescriptors); Assert.Equal(0, provider.CalledGetExportDescriptors); Assert.Equal(10, container.GetExport <int>()); Assert.Equal(1, provider.CalledGetExportDescriptors); Assert.Equal(1, provider.CalledGetExportDescriptors); }
private void Compose(string service) { try { // set the path to the plugins directory string path = "C:\\Users\\david.renz\\Documents\\_work\\Projects\\SMS\\code_demo\\SMSService_Demo2\\plugins\\" + service + ".dll"; Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(path); Type type = assembly.GetType(assembly.DefinedTypes.First().FullName); // Method one --> using the container ContainerConfiguration config = new ContainerConfiguration().WithAssembly(assembly); compContainer = config.CreateContainer(); MessageService = compContainer.GetExport <IMessage>(); // Method two --> without the container //MessageService = Activator.CreateInstance(type) as IMessage; } catch { throw new Exception("Could not load selected service."); } }
public static T GetInstance <T>(string assemblyHint = null, string typeName = null) { var type = default(T); if (container == null) { return(type); } if (string.IsNullOrWhiteSpace(typeName)) { type = container.GetExport <T>(); } else { var exports = container.GetExports <T>(); type = exports.FirstOrDefault(x => x.GetType().Name == typeName && (assemblyHint == null || (x.GetType().AssemblyQualifiedName != null && x.GetType().AssemblyQualifiedName.Contains(assemblyHint)))); } return(type); }
public void Configure( IApplicationBuilder app, IServiceProvider serviceProvider, ILoggerFactory loggerFactory, HttpEnvironment httpEnvironment) { var workspace = _compositionHost.GetExport <OmniSharpWorkspace>(); var logger = loggerFactory.CreateLogger <Startup>(); logger.LogInformation($"Starting OmniSharp on {Platform.Current}"); app.UseRequestLogging(); app.UseExceptionHandler("/error"); app.UseMiddleware <EndpointMiddleware>(_compositionHost); app.UseMiddleware <StatusMiddleware>(workspace); app.UseMiddleware <StopServerMiddleware>(); WorkspaceInitializer.Initialize(serviceProvider, _compositionHost); logger.LogInformation($"Omnisharp server running on port '{httpEnvironment.Port}' at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}."); }
public void Configure( IApplicationBuilder app, IServiceProvider serviceProvider, ILoggerFactory loggerFactory, IEventEmitter eventEmitter, ISharedTextWriter writer, HttpEnvironment httpEnvironment, IOptionsMonitor <OmniSharpOptions> options) { var workspace = _compositionHost.GetExport <OmniSharpWorkspace>(); var logger = loggerFactory.CreateLogger <Startup>(); loggerFactory.AddConsole((category, level) => { if (HostHelpers.LogFilter(category, level, _environment)) { return(true); } if (string.Equals(category, typeof(ExceptionHandlerMiddleware).FullName, StringComparison.OrdinalIgnoreCase)) { return(true); } return(false); }); logger.LogInformation($"Starting OmniSharp on {Platform.Current}"); app.UseRequestLogging(); app.UseExceptionHandler("/error"); app.UseMiddleware <EndpointMiddleware>(_compositionHost); app.UseMiddleware <StatusMiddleware>(workspace); app.UseMiddleware <StopServerMiddleware>(); WorkspaceInitializer.Initialize(serviceProvider, _compositionHost, _configuration, logger); logger.LogInformation($"Omnisharp server running on port '{httpEnvironment.Port}' at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}."); }
private Task Initialize(InitializeParams initializeParams) { CreateCompositionHost(initializeParams); // TODO: Make it easier to resolve handlers from MEF (without having to add more attributes to the services if we can help it) var workspace = _compositionHost.GetExport <OmniSharpWorkspace>(); _server.AddHandlers(TextDocumentSyncHandler.Enumerate(_handlers, workspace)); _server.AddHandlers(DefinitionHandler.Enumerate(_handlers)); _server.AddHandlers(HoverHandler.Enumerate(_handlers)); _server.AddHandlers(CompletionHandler.Enumerate(_handlers)); _server.AddHandlers(SignatureHelpHandler.Enumerate(_handlers)); _server.AddHandlers(RenameHandler.Enumerate(_handlers)); _server.AddHandlers(DocumentSymbolHandler.Enumerate(_handlers)); _server.LogMessage(new LogMessageParams() { Message = "Added handlers... waiting for initialize...", Type = MessageType.Log }); return(Task.CompletedTask); }
/// <summary> /// Used to override the default conventions for controller/part dependency injection. /// Cannot be used in conjunction with any other methods on this type. Most applications /// should not use this method. /// </summary> /// <param name="configuration">A configuration containing the controller types and other parts that /// should be used by the composition provider.</param> public static void SetConfiguration(ContainerConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException("catalog"); } if (IsInitialized) { throw new InvalidOperationException("Already initialized."); } // We add RSF with no conventions (overriding anything set as the default in configuration) _container = configuration.CreateContainer(); var factoryContract = new CompositionContract(typeof(ExportFactory <CompositionContext>), null, new Dictionary <string, object> { { "SharingBoundaryNames", new[] { Boundaries.HttpRequest, Boundaries.DataConsistency, Boundaries.UserIdentity } } }); _requestScopeFactory = (ExportFactory <CompositionContext>)_container.GetExport(factoryContract); ConfigureMvc(); ConfigureWebApi(); }
protected override object GetInstance(Type serviceType, string key) { return(_compositionHost.GetExport(serviceType, key)); }
public TService GetService <TService>() { return(_compositionContext.GetExport <TService>()); }
public RoslynHost(NuGetConfiguration nuGetConfiguration = null, IEnumerable <Assembly> additionalAssemblies = null) { _nuGetConfiguration = nuGetConfiguration; _workspaces = new ConcurrentDictionary <DocumentId, RoslynWorkspace>(); _diagnosticsUpdatedNotifiers = new ConcurrentDictionary <DocumentId, Action <DiagnosticsUpdatedArgs> >(); var assemblies = new[] { Assembly.Load("Microsoft.CodeAnalysis"), Assembly.Load("Microsoft.CodeAnalysis.CSharp"), Assembly.Load("Microsoft.CodeAnalysis.Features"), Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features"), typeof(RoslynHost).Assembly, }; if (additionalAssemblies != null) { assemblies = assemblies.Concat(additionalAssemblies).ToArray(); } var editorFeaturesAssembly = Assembly.Load("Microsoft.CodeAnalysis.EditorFeatures"); var editorFeaturesTypes = SafeGetAssemblyTypes(editorFeaturesAssembly); // we can't import this entire assembly due to composition errors // and we don't need all the VS services var editorFeaturesParts = editorFeaturesTypes .Where(x => x.Namespace == "Microsoft.CodeAnalysis.CodeFixes") .Concat(new[] { typeof(DocumentationProviderServiceFactory) }); _compositionContext = new ContainerConfiguration() .WithAssemblies(MefHostServices.DefaultAssemblies.Concat(assemblies)) .WithParts(editorFeaturesParts) .WithDefaultConventions(new AttributeFilterProvider()) .CreateContainer(); _host = MefHostServices.Create(_compositionContext); _parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Script); _referenceAssembliesPath = GetReferenceAssembliesPath(); _documentationProviderService = new DocumentationProviderServiceFactory.DocumentationProviderService(); DefaultReferences = _defaultReferenceAssemblies.Select(t => (MetadataReference)MetadataReference.CreateFromFile(t.Location, documentation: GetDocumentationProvider(t.Location))).ToImmutableArray(); DefaultImports = _defaultReferenceAssemblyTypes.Select(x => x.Namespace).Distinct().ToImmutableArray(); GetService <IDiagnosticService>().DiagnosticsUpdated += OnDiagnosticsUpdated; _compositionContext.GetExport <ISemanticChangeNotificationService>().OpenedDocumentSemanticChanged += OnOpenedDocumentSemanticChanged; // MEF v1 var csharpEditorFeatures = Assembly.Load("Microsoft.CodeAnalysis.CSharp.EditorFeatures"); var container = new CompositionContainer(new AggregateCatalog( new TypeCatalog(editorFeaturesTypes), new TypeCatalog(SafeGetAssemblyTypes(csharpEditorFeatures)), new AssemblyCatalog(typeof(RoslynHost).Assembly)), CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); ((AggregateSignatureHelpProvider)GetService <ISignatureHelpProvider>()).Initialize(container); CompletionService.Initialize(container); }
public ICombined ResolveCombined() => container.GetExport <ICombined>();
private IDictionary <string, Lazy <EndpointHandler> > Initialize() { var workspace = _compositionHost.GetExport <OmniSharpWorkspace>(); var projectSystems = _compositionHost.GetExports <IProjectSystem>(); var endpointMetadatas = _compositionHost.GetExports <Lazy <IRequest, OmniSharpEndpointMetadata> >() .Select(x => x.Metadata) .ToArray(); var handlers = _compositionHost.GetExports <Lazy <IRequestHandler, OmniSharpRequestHandlerMetadata> >(); var updateBufferEndpointHandler = new Lazy <EndpointHandler <UpdateBufferRequest, object> >( () => (EndpointHandler <UpdateBufferRequest, object>)_endpointHandlers[OmniSharpEndpoints.UpdateBuffer].Value); var languagePredicateHandler = new LanguagePredicateHandler(projectSystems); var projectSystemPredicateHandler = new StaticLanguagePredicateHandler("Projects"); var nugetPredicateHandler = new StaticLanguagePredicateHandler("NuGet"); var endpointHandlers = endpointMetadatas.ToDictionary( x => x.EndpointName, endpoint => new Lazy <EndpointHandler>(() => { IPredicateHandler handler; // Projects are a special case, this allows us to select the correct "Projects" language for them if (endpoint.EndpointName == OmniSharpEndpoints.ProjectInformation || endpoint.EndpointName == OmniSharpEndpoints.WorkspaceInformation) { handler = projectSystemPredicateHandler; } else if (endpoint.EndpointName == OmniSharpEndpoints.PackageSearch || endpoint.EndpointName == OmniSharpEndpoints.PackageSource || endpoint.EndpointName == OmniSharpEndpoints.PackageVersion) { handler = nugetPredicateHandler; } else { handler = languagePredicateHandler; } // This lets any endpoint, that contains a Request object, invoke update buffer. // The language will be same language as the caller, this means any language service // must implement update buffer. var updateEndpointHandler = updateBufferEndpointHandler; if (endpoint.EndpointName == OmniSharpEndpoints.UpdateBuffer) { // We don't want to call update buffer on update buffer. updateEndpointHandler = new Lazy <EndpointHandler <UpdateBufferRequest, object> >(() => null); } return(EndpointHandler.Factory(handler, _compositionHost, _logger, endpoint, handlers, updateEndpointHandler, Enumerable.Empty <Plugin>())); }), StringComparer.OrdinalIgnoreCase ); // Handled as alternative middleware in http endpointHandlers.Add( OmniSharpEndpoints.CheckAliveStatus, new Lazy <EndpointHandler>( () => new GenericEndpointHandler(x => Task.FromResult <object>(true))) ); endpointHandlers.Add( OmniSharpEndpoints.CheckReadyStatus, new Lazy <EndpointHandler>( () => new GenericEndpointHandler(x => Task.FromResult <object>(workspace.Initialized))) ); endpointHandlers.Add( OmniSharpEndpoints.StopServer, new Lazy <EndpointHandler>( () => new GenericEndpointHandler(x => { _cancellationTokenSource.Cancel(); return(Task.FromResult <object>(null)); })) ); return(endpointHandlers); }
public static object Get(Type t, string contract = null) { return(s_compositionHost.GetExport(t, contract)); }
internal static RequestHandlers ConfigureCompositionHost(ILanguageServer server, CompositionHost compositionHost) { var projectSystems = compositionHost.GetExports <IProjectSystem>(); var documentSelectors = projectSystems .GroupBy(x => x.Language) .Select(x => ( language: x.Key, selector: new DocumentSelector(x .SelectMany(z => z.Extensions) .Distinct() .SelectMany(z => { if (x.Key == LanguageNames.CSharp && z == ".cs") { return(new[] { new DocumentFilter() { Pattern = $"**/*{z}" }, new DocumentFilter() { Scheme = "csharp" } }); } return(new[] { new DocumentFilter() { Pattern = $"**/*{z}" }, }); }) ) )) .ToArray(); var logger = compositionHost.GetExport <ILoggerFactory>().CreateLogger <LanguageServerHost>(); logger.LogTrace( "Configured Document Selectors {@DocumentSelectors}", documentSelectors.Select(x => new { x.language, x.selector }) ); var omnisharpRequestHandlers = compositionHost.GetExports <Lazy <IRequestHandler, OmniSharpRequestHandlerMetadata> >(); // TODO: Get these with metadata so we can attach languages // This will then let us build up a better document filter, and add handles foreach type of handler // This will mean that we will have a strategy to create handlers from the interface type var handlers = new RequestHandlers(omnisharpRequestHandlers, documentSelectors); logger.LogTrace("--- Handler Definitions ---"); foreach (var handlerCollection in handlers) { foreach (var handler in handlerCollection) { logger.LogTrace( "Handler: {Language}:{DocumentSelector}:{Handler}", handlerCollection.Language, handlerCollection.DocumentSelector.ToString(), handler.GetType().FullName ); } } // the goal here is add interoperability between omnisharp and LSP // This way an existing client (say vscode) that is using the custom omnisharp protocol can migrate to the new one // and not loose any functionality. server.Register(r => { var defaultOptions = new JsonRpcHandlerOptions() { RequestProcessType = RequestProcessType.Parallel }; var interop = InitializeInterop(compositionHost); foreach (var osHandler in interop) { var method = $"o#/{osHandler.Key.Trim('/').ToLowerInvariant()}"; r.OnJsonRequest(method, CreateInteropHandler(osHandler.Value), defaultOptions); logger.LogTrace("O# Handler: {Method}", method); }
public T GetService <T>() { return(_container.GetExport <T>()); }
public RoslynHost(INuGetProvider nuGetProvider = null) { _nuGetProvider = nuGetProvider; _referencesDirectives = new ConcurrentDictionary <string, DirectiveInfo>(); _referenceDirectivesLock = new SemaphoreSlim(1, 1); var assemblies = new[] { Assembly.Load("Microsoft.CodeAnalysis"), Assembly.Load("Microsoft.CodeAnalysis.CSharp"), Assembly.Load("Microsoft.CodeAnalysis.Features"), Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features"), typeof(RoslynHost).Assembly, }; // we can't import this entire assembly due to composition errors // and we don't need all the VS services var editorFeaturesAssembly = Assembly.Load("Microsoft.CodeAnalysis.EditorFeatures"); var types = editorFeaturesAssembly.GetTypes().Where(x => x.Namespace == "Microsoft.CodeAnalysis.CodeFixes"); _compositionContext = new ContainerConfiguration() .WithAssemblies(MefHostServices.DefaultAssemblies.Concat(assemblies)) .WithParts(types) .WithDefaultConventions(new AttributeFilterProvider()) .CreateContainer(); var host = MefHostServices.Create(_compositionContext); _workspace = new RoslynWorkspace(host, this); _workspace.ApplyingTextChange += (d, s) => ApplyingTextChange?.Invoke(d, s); _parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Script); _referenceAssembliesPath = GetReferenceAssembliesPath(); _documentationProviderService = new DocumentationProviderServiceFactory.DocumentationProviderService(); _references = _defaultReferenceAssemblies.Select(t => (MetadataReference)MetadataReference.CreateFromFile(t.Location, documentation: GetDocumentationProvider(t.Location))).ToImmutableArray(); var metadataReferenceResolver = CreateMetadataReferenceResolver(); _compilationOptions = new CSharpCompilationOptions(OutputKind.NetModule, usings: _defaultReferenceAssemblyTypes.Select(x => x.Namespace).ToImmutableArray(), metadataReferenceResolver: metadataReferenceResolver); _workspace.Services.GetService <Microsoft.CodeAnalysis.SolutionCrawler.ISolutionCrawlerRegistrationService>() .Register(_workspace); _compositionContext.GetExport <ISemanticChangeNotificationService>().OpenedDocumentSemanticChanged += OnOpenedDocumentSemanticChanged; // MEF v1 var container = new CompositionContainer(new AggregateCatalog( new AssemblyCatalog(Assembly.Load("Microsoft.CodeAnalysis.EditorFeatures")), new AssemblyCatalog(Assembly.Load("Microsoft.CodeAnalysis.CSharp.EditorFeatures")), new AssemblyCatalog(typeof(RoslynHost).Assembly)), CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); ((AggregateSignatureHelpProvider)GetService <ISignatureHelpProvider>()).Initialize(container); CompletionService.Initialize(container); }
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider, IOmnisharpEnvironment env, ILoggerFactory loggerFactory, ISharedTextWriter writer, IOmnisharpAssemblyLoader loader, IOptions <OmniSharpOptions> optionsAccessor) { Func <RuntimeLibrary, bool> shouldLoad = lib => lib.Dependencies.Any(dep => dep.Name == "OmniSharp.Abstractions" || dep.Name == "OmniSharp.Roslyn"); var dependencyContext = DependencyContext.Default; var assemblies = dependencyContext.RuntimeLibraries .Where(shouldLoad) .SelectMany(lib => lib.GetDefaultAssemblyNames(dependencyContext)) .Select(each => loader.Load(each.Name)) .ToList(); PluginHost = ConfigureMef(serviceProvider, optionsAccessor.Value, assemblies); Workspace = PluginHost.GetExport <OmnisharpWorkspace>(); if (env.TransportType == TransportType.Stdio) { loggerFactory.AddStdio(writer, (category, level) => LogFilter(category, level, env)); } else { loggerFactory.AddConsole((category, level) => LogFilter(category, level, env)); } var logger = loggerFactory.CreateLogger <Startup>(); foreach (var assembly in assemblies) { logger.LogDebug($"Loaded {assembly.FullName}"); } app.UseRequestLogging(); app.UseExceptionHandler("/error"); app.UseMiddleware <EndpointMiddleware>(); app.UseMiddleware <StatusMiddleware>(); app.UseMiddleware <StopServerMiddleware>(); if (env.TransportType == TransportType.Stdio) { logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{env.Path}' on host {env.HostPID}."); } else { logger.LogInformation($"Omnisharp server running on port '{env.Port}' at location '{env.Path}' on host {env.HostPID}."); } // ProjectEventForwarder register event to OmnisharpWorkspace during instantiation PluginHost.GetExport <ProjectEventForwarder>(); // Initialize all the project systems foreach (var projectSystem in PluginHost.GetExports <IProjectSystem>()) { try { projectSystem.Initalize(Configuration.GetSection(projectSystem.Key)); } catch (Exception e) { var message = $"The project system '{projectSystem.GetType().Name}' threw exception during initialization.\n{e.Message}\n{e.StackTrace}"; // if a project system throws an unhandled exception it should not crash the entire server logger.LogError(message); } } // Mark the workspace as initialized Workspace.Initialized = true; logger.LogInformation("Configuration finished."); }
private static void PerformOperations <T>(CompositionHost container, T a, T b) { container .GetExport <Calculator <T> >() .PerformOperations(a, b); }
public void Export_When_Property_Is_Null_Should_Work_And_Import_Null() { mContainer.GetExport <Importer>().Db.Should().BeNull(); }
protected T GetInstance <T>() { return(container.GetExport <T>()); }
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider, IOmnisharpEnvironment env, ILoggerFactory loggerFactory, ISharedTextWriter writer, IOptions <OmniSharpOptions> optionsAccessor) { var assemblies = DnxPlatformServices.Default.LibraryManager.GetReferencingLibraries("OmniSharp.Abstractions") .SelectMany(libraryInformation => libraryInformation.Assemblies) .Concat( DnxPlatformServices.Default.LibraryManager.GetReferencingLibraries("OmniSharp.Roslyn") .SelectMany(libraryInformation => libraryInformation.Assemblies) ) .Select(assemblyName => Assembly.Load(assemblyName)); PluginHost = ConfigureMef(serviceProvider, optionsAccessor.Value, assemblies); Workspace = PluginHost.GetExport <OmnisharpWorkspace>(); if (env.TransportType == TransportType.Stdio) { loggerFactory.AddStdio(writer, (category, level) => LogFilter(category, level, env)); } else { loggerFactory.AddConsole((category, level) => LogFilter(category, level, env)); } var logger = loggerFactory.CreateLogger <Startup>(); app.UseRequestLogging(); app.UseExceptionHandler("/error"); app.UseMiddleware <EndpointMiddleware>(); app.UseMiddleware <StatusMiddleware>(); app.UseMiddleware <StopServerMiddleware>(); if (env.TransportType == TransportType.Stdio) { logger.LogInformation($"Omnisharp server running using stdio at location '{env.Path}' on host {env.HostPID}."); } else { logger.LogInformation($"Omnisharp server running on port '{env.Port}' at location '{env.Path}' on host {env.HostPID}."); } // Forward workspace events PluginHost.GetExport <ProjectEventForwarder>(); foreach (var projectSystem in PluginHost.GetExports <IProjectSystem>()) { try { projectSystem.Initalize(Configuration.GetSection(projectSystem.Key)); } catch (Exception e) { //if a project system throws an unhandled exception //it should not crash the entire server logger.LogError($"The project system '{projectSystem.GetType().Name}' threw an exception.", e); } } // Mark the workspace as initialized Workspace.Initialized = true; logger.LogInformation("Solution has finished loading"); }
public static T GetExportedValue <T>() => _container.GetExport <T>();