Beispiel #1
0
 public void TestAddDuplicateService2()
 {
   ServiceProvider provider = new ServiceProvider();
   provider.Add<ILog>(new ServiceCreatorCallback<ILog>(ServiceRequested));
   ILog log1 = new NoLog();
   provider.Add<ILog>(log1);
 }
Beispiel #2
0
        public static ServiceProvider CreateTestServices(
            IServiceProvider applicationServices,
            Project project,
            ReportingChannel channel)
        {
            var services = new ServiceProvider(applicationServices);

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(new TestHostLoggerProvider(channel));
            services.Add(typeof(ILoggerFactory), loggerFactory);

            var libraryExporter = applicationServices.GetRequiredService <ILibraryExporter>();
            var export          = libraryExporter.GetExport(project.Name);

            var projectReference = export.MetadataReferences
                                   .OfType <IMetadataProjectReference>()
                                   .Where(r => r.Name == project.Name)
                                   .FirstOrDefault();

            services.Add(
                typeof(ISourceInformationProvider),
                new SourceInformationProvider(projectReference, loggerFactory.CreateLogger <SourceInformationProvider>()));

            services.Add(typeof(ITestDiscoverySink), new TestDiscoverySink(channel));
            services.Add(typeof(ITestExecutionSink), new TestExecutionSink(channel));

            return(services);
        }
Beispiel #3
0
        public Task <int> Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("{app} [arguments]");
                return(Task.FromResult(-1));
            }

            var name        = args[0];
            var programArgs = args.Skip(1).ToArray();

            var assembly = Assembly.Load(new AssemblyName(name));

            if (assembly == null)
            {
                return(Task.FromResult(-1));
            }

#if ASPNET50
            string applicationBaseDirectory;
            if (PlatformHelper.IsMono)
            {
                applicationBaseDirectory = Environment.GetEnvironmentVariable(EnvironmentNames.AppBase);

                if (string.IsNullOrEmpty(applicationBaseDirectory))
                {
                    applicationBaseDirectory = Directory.GetCurrentDirectory();
                }
            }
            else
            {
                applicationBaseDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            }
#else
            string applicationBaseDirectory = AppContext.BaseDirectory;
#endif

            var framework     = Environment.GetEnvironmentVariable("TARGET_FRAMEWORK") ?? Environment.GetEnvironmentVariable(EnvironmentNames.Framework);
            var configuration = Environment.GetEnvironmentVariable("TARGET_CONFIGURATION") ?? Environment.GetEnvironmentVariable(EnvironmentNames.Configuration) ?? "Debug";

            // TODO: Support the highest installed version
            var targetFramework = FrameworkNameUtility.ParseFrameworkName(framework ?? "aspnet50");

            var applicationEnvironment = new ApplicationEnvironment(applicationBaseDirectory,
                                                                    targetFramework,
                                                                    configuration,
                                                                    assembly: assembly);

            CallContextServiceLocator.Locator = new ServiceProviderLocator();

            var serviceProvider = new ServiceProvider();
            serviceProvider.Add(typeof(IAssemblyLoaderContainer), _container);
            serviceProvider.Add(typeof(IAssemblyLoadContextAccessor), LoadContextAccessor.Instance);
            serviceProvider.Add(typeof(IApplicationEnvironment), applicationEnvironment);

            CallContextServiceLocator.Locator.ServiceProvider = serviceProvider;

            return(EntryPointExecutor.Execute(assembly, programArgs, serviceProvider));
        }
Beispiel #4
0
 public void TestAddDuplicateService1()
 {
   ServiceProvider provider = new ServiceProvider();
   ILog log1 = new NoLog();
   ILog log2 = new NoLog();
   provider.Add<ILog>(log1);
   provider.Add<ILog>(log2);
 }
Beispiel #5
0
        public void TestAddDuplicateService2()
        {
            ServiceProvider provider = new ServiceProvider();

            provider.Add <ILog>(new ServiceCreatorCallback <ILog>(ServiceRequested));
            ILog log1 = new NoLog();

            provider.Add <ILog>(log1);
        }
Beispiel #6
0
        public void TestAddDuplicateService1()
        {
            ServiceProvider provider = new ServiceProvider();
            ILog            log1     = new NoLog();
            ILog            log2     = new NoLog();

            provider.Add <ILog>(log1);
            provider.Add <ILog>(log2);
        }
Beispiel #7
0
        internal Core(ISettings settings, IInteractionService interactionService, IDispatcher dispatcher)
        {
            _logger.Info("Creating new core instance");
            var state = new InternalState(settings);

            var services = new ServiceProvider();

            services.Add <IAsyncVoidExecutor>(new AsyncVoidExecutor());
            services.Add(Types.Default);
            services.Add(dispatcher);
            services.Add(interactionService);
            services.Add <IDialogService>(new DialogService(services));
            services.Add <IEventManager>(new EventManager());
            services.Add <IRepositoryStateService>(new RepositoryStateService(services));

            // TODO: should this be registered somewhere?
            new PresetGeneratorService(services);

            var model = new Model.Model(state, services, state.CheckIsFirstStart());

            services.Add <IModel>(model);

            // TODO: should we use different service providers to avoid accidental abuse?
            _viewModel = new ViewModel.ViewModel(services);
            model.Load();
        }
        public void OnGet_ItShouldResolveAllInstances()
        {
            //Arrange
            var subject = new ServiceProvider();

            subject.Add <ITest1, Test1>();
            subject.Add <ITest2, Test2>();
            subject.Add <ITest3, Test3>();

            //Act
            var result = subject.Get <ITest1>();

            //Assert
            Assert.NotNull(result.Test2.Test3);
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var mailServiceProvider = new ServiceProvider();

            mailServiceProvider.Add(this.messageStore);
            mailServiceProvider.Add(this.serviceProvider.Resolve <MailboxFilter>());
            this.smtpServer = new SmtpServer.SmtpServer(this.options, mailServiceProvider);

            this.smtpServer.SessionCreated   += this.SmtpServer_SessionCreated;
            this.smtpServer.SessionFaulted   += this.SmtpServer_SessionFaulted;
            this.smtpServer.SessionCompleted += this.SmtpServer_SessionCompleted;

            _ = this.smtpServer.StartAsync(CancellationToken.None);
            return(Task.CompletedTask);
        }
Beispiel #10
0
        public Task <int> Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("{app} [arguments]");
                return(Task.FromResult(-1));
            }

            var name        = args[0];
            var programArgs = args.Skip(1).ToArray();

            var assembly = Assembly.Load(new AssemblyName(name));

            if (assembly == null)
            {
                return(Task.FromResult(-1));
            }

#if NET45
            // REVIEW: Need a way to set the application base on mono
            string applicationBaseDirectory = PlatformHelper.IsMono ?
                                              Directory.GetCurrentDirectory() :
                                              AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
#else
            string applicationBaseDirectory = ApplicationContext.BaseDirectory;
#endif

            var framework     = Environment.GetEnvironmentVariable("TARGET_FRAMEWORK") ?? Environment.GetEnvironmentVariable("KRE_FRAMEWORK");
            var configuration = Environment.GetEnvironmentVariable("TARGET_CONFIGURATION") ?? Environment.GetEnvironmentVariable("KRE_CONFIGURATION") ?? "Debug";

            var targetFramework = FrameworkNameUtility.ParseFrameworkName(framework ?? (PlatformHelper.IsMono ? "net45" : "net451"));

            var applicationEnvironment = new ApplicationEnvironment(applicationBaseDirectory,
                                                                    targetFramework,
                                                                    configuration,
                                                                    assembly: assembly);

            CallContextServiceLocator.Locator = new ServiceProviderLocator();

            var serviceProvider = new ServiceProvider();
            serviceProvider.Add(typeof(IAssemblyLoaderContainer), _container);
            serviceProvider.Add(typeof(IAssemblyLoaderEngine), _loaderEngine);
            serviceProvider.Add(typeof(IApplicationEnvironment), applicationEnvironment);

            CallContextServiceLocator.Locator.ServiceProvider = serviceProvider;

            return(EntryPointExecutor.Execute(assembly, programArgs, serviceProvider));
        }
Beispiel #11
0
        public CompilationEngine(
            CompilationCache compilationCache,
            CompilationEngineContext context)
        {
            _context             = context;
            RootLibraryExporter  = new LibraryExporter(_context.LibraryManager, this, _context.TargetFramework, _context.Configuration);
            _compilerLoadContext = new Lazy <IAssemblyLoadContext>(() =>
            {
                var factory = (IAssemblyLoadContextFactory)_context.Services.GetService(typeof(IAssemblyLoadContextFactory));

                // Ensure this compilation engine is in the service provider
                var services = new ServiceProvider(_context.Services);
                services.Add(typeof(ICompilationEngine), this);
                return(factory.Create(services));
            });

            CompilationCache = compilationCache;

            // Register compiler services
            // TODO(anurse): Switch to project factory model to avoid needing to do this.
            _context.AddService(typeof(ICache), CompilationCache.Cache);
            _context.AddService(typeof(ICacheContextAccessor), CompilationCache.CacheContextAccessor);
            _context.AddService(typeof(INamedCacheDependencyProvider), CompilationCache.NamedCacheDependencyProvider);
            _context.AddService(typeof(IFileWatcher), context.FileWatcher);
        }
Beispiel #12
0
        public static void Main(string[] args)
        {
            ServiceProvider.Add <ILogService>(new ConsoleLog());
            ServiceProvider.Add <ILogService>(new FileLog());
            ServiceProvider.Add <IMonitorService>(new ConsoleMonitor());
            ServiceProvider.Add <IMonitorService>(new FileMonitor());
            ServiceProvider.Add <IMonitorService>(new HttpMonitor(ConfigurationManager.Get("statusHost")));

            //var start = DateTime.Now;
            JdSkuSampleSpider spiderBuilder = new JdSkuSampleSpider();

            spiderBuilder.Run("rerun");
            //var end = DateTime.Now;
            //Console.WriteLine((end - start).TotalMilliseconds);
            //Console.Read();
            //SpiderExample.Run();
            //JdSkuSampleSpider spiderBuilder = new JdSkuSampleSpider();
            //var context = spiderBuilder.GetBuilder().Context;
            //ContextSpider spider = new ContextSpider(context);
            //spider.Run("rerun");


            //EmailClient client = new EmailClient("smtp.163.com", "*****@*****.**", "zousong.88");
            //var msg = new EmaillMessage("test", "test", "*****@*****.**" );
            //client.SendMail(msg);
        }
Beispiel #13
0
 public void TestServiceCreatorCallback()
 {
   ServiceProvider provider = new ServiceProvider();
   provider.Add<ILog>(new ServiceCreatorCallback<ILog>(ServiceRequested));
   ILog log = provider.Get<ILog>();
   Assert.IsNotNull(log);
 }
Beispiel #14
0
        public void OnGet_ItShouldResolveType()
        {
            //Arrange
            var serviceProvider = new ServiceProvider();

            serviceProvider.Add(typeof(IRepository <Entity>), typeof(FakeSqlRepository <Entity>));
            serviceProvider.Add(typeof(IRepository <>), typeof(SqlRepository <>));
            serviceProvider.Add <IHandler, Handler>();

            //Act
            var result = serviceProvider.Get <IHandler>();

            //Assert
            Assert.True(result.FakeRepository is FakeSqlRepository <Entity>);
            Assert.True(result.Repository is SqlRepository <BaseEntity>);
        }
        public static void Run()
        {
            var cancellationTokenSource = new CancellationTokenSource();

            var options = new SmtpServerOptionsBuilder()
                          .ServerName("SmtpServer SampleApp")
                          .Port(9025)
                          .Build();

            var serviceProvider = new ServiceProvider();

            serviceProvider.Add(new SampleMailboxFilter(TimeSpan.FromSeconds(5)));

            var server = new SmtpServer.SmtpServer(options, serviceProvider);

            server.SessionCreated   += OnSessionCreated;
            server.SessionCompleted += OnSessionCompleted;
            server.SessionFaulted   += OnSessionFaulted;
            server.SessionCancelled += OnSessionCancelled;

            var serverTask = server.StartAsync(cancellationTokenSource.Token);

            // ReSharper disable once MethodSupportsCancellation
            Task.Run(() => SampleMailClient.Send());

            Console.WriteLine("Press any key to cancel the server.");
            Console.ReadKey();

            Console.WriteLine("Forcibily cancelling the server and any active sessions");

            cancellationTokenSource.Cancel();
            serverTask.WaitWithoutException();

            Console.WriteLine("The server has been cancelled.");
        }
Beispiel #16
0
        public static void Run()
        {
            var cancellationTokenSource = new CancellationTokenSource();

            var options = new SmtpServerOptionsBuilder()
                          .ServerName("SmtpServer SampleApp")
                          .Certificate(CreateCertificate())
                          .Endpoint(builder =>
                                    builder
                                    .Port(9025, true)
                                    .AllowUnsecureAuthentication(false))
                          .Build();

            var serviceProvider = new ServiceProvider();

            serviceProvider.Add(new CustomEndpointListenerFactory());

            var server = new SmtpServer.SmtpServer(options, serviceProvider);

            var serverTask = server.StartAsync(cancellationTokenSource.Token);

            SampleMailClient.Send(useSsl: true);

            cancellationTokenSource.Cancel();
            serverTask.WaitWithoutException();
        }
Beispiel #17
0
        public void WhenUnableToResolve3_ItShouldThrow()
        {
            //Arrange
            var serviceProvider = new ServiceProvider();

            serviceProvider.Add <RootClass>();
            serviceProvider.Add <InnerClass1>();

            //Act
            var invalidOperationException = Assert.Throws <InvalidOperationException>(() => serviceProvider.Get <RootClass>());

            //Assert
            var expectedMessage = $"Unable to resolve type '{typeof(InnerClass2).FullName}' while attempting to activate '{typeof(InnerClass1).FullName}'.";

            Assert.Equal(expectedMessage, invalidOperationException.Message);
        }
        public void OnGet_ItShouldResolveTheSameInstance()
        {
            //Arrange
            var subject = new ServiceProvider();

            subject.Add <ITest1, Test1>();
            subject.Add <ITest2, Test2>();
            subject.Add(typeof(ITest3), typeof(Test3));

            //Act
            var test1 = subject.Get <ITest1>();
            var test3 = subject.Get <ITest3>();

            //Assert
            Assert.Same(test1.Test2.Test3, test3);
        }
        public static void Run()
        {
            _cancellationTokenSource = new CancellationTokenSource();

            var options = new SmtpServerOptionsBuilder()
                          .ServerName("SmtpServer SampleApp")
                          .Endpoint(builder =>
                                    builder
                                    .AllowUnsecureAuthentication()
                                    .AuthenticationRequired()
                                    .Port(9025))
                          .Build();

            var serviceProvider = new ServiceProvider();

            serviceProvider.Add(new AuthenticationHandler());

            var server = new SmtpServer.SmtpServer(options, serviceProvider);

            server.SessionCreated   += OnSessionCreated;
            server.SessionCompleted += OnSessionCompleted;

            var serverTask = server.StartAsync(_cancellationTokenSource.Token);

            SampleMailClient.Send(user: "******", password: "******", count: 5);

            serverTask.WaitWithoutException();
        }
        public async void Start()
        {
            _cancellationTokenSource = new CancellationTokenSource();

            var telegramSettings       = TelegramConfiguration.Read();
            var telegramAsMessageStore = new TelegramAsMessageStore(telegramSettings.Token, telegramSettings.ChatId);

            var smtpSettings = SmtpConfiguration.Read();
            var options      = new SmtpServerOptionsBuilder()
                               .Port(smtpSettings.Port)
                               .Build();

            var serviceProvider = new ServiceProvider();

            serviceProvider.Add(telegramAsMessageStore);

            var smtpServer = new SmtpServer.SmtpServer(options, serviceProvider);

            _ = new SmtpSessionLogger(smtpServer, _log);
            await smtpServer.StartAsync(_cancellationTokenSource.Token);

            if (Environment.UserInteractive)
            {
                _log.Warn($"{ServiceName} started in interactive mode");
            }
            else
            {
                _log.Warn($"{ServiceName} service started");
            }
        }
        public static void Run()
        {
            // this is important when dealing with a certificate that isnt valid
            ServicePointManager.ServerCertificateValidationCallback = IgnoreCertificateValidationFailureForTestingOnly;

            var cancellationTokenSource = new CancellationTokenSource();

            var options = new SmtpServerOptionsBuilder()
                          .ServerName("SmtpServer SampleApp")
                          .Endpoint(builder =>
                                    builder
                                    .Port(9025, true)
                                    .AllowUnsecureAuthentication(false)
                                    .Certificate(CreateCertificate()))
                          .Build();

            var serviceProvider = new ServiceProvider();

            serviceProvider.Add(new SampleUserAuthenticator());

            var server = new SmtpServer.SmtpServer(options, serviceProvider);

            server.SessionCreated += OnSessionCreated;

            var serverTask = server.StartAsync(cancellationTokenSource.Token);

            SampleMailClient.Send(user: "******", password: "******", useSsl: true);

            cancellationTokenSource.Cancel();
            serverTask.WaitWithoutException();
        }
Beispiel #22
0
        private void RegisterConfigurationProvider()
        {
            var configurationKeys = new Dictionary <string, ConfigurationPropertyMetadata[]>()
            {
                {
                    "Storage",
                    new[]
                    {
                        new ConfigurationPropertyMetadata
                        {
                            Name = "Provider", Type = typeof(string)
                        },
                        new ConfigurationPropertyMetadata
                        {
                            Name = "Storage", Type = typeof(string)
                        }
                    }
                }
            };

            var configurationProvider =
                new SimpleConfigurationProvider(configurationKeys);

            ServiceProvider.Add <IConfigurationProvider>(configurationProvider);
        }
Beispiel #23
0
        public static ServiceProvider Create()
        {
            var services = new ServiceProvider();

            DoCallback((service, implementation) => services.Add(service, implementation));
            return(services);
        }
        public void OnGet_WithAddInstance_ItShouldResolveTheSameInstance()
        {
            //Arrange
            var subject          = new ServiceProvider();
            var expectedInstance = new Test3();

            subject.Add <ITest1, Test1>();
            subject.Add <ITest2, Test2>();
            subject.Add <ITest3>(expectedInstance);

            //Act
            var result = subject.Get <ITest3>();

            //Assert
            Assert.Same(expectedInstance, result);
        }
Beispiel #25
0
        /// <summary>
        /// This method registers services with the service provider.
        /// </summary>
        private void FetchCoreServiceTypes()
        {
            try
            {
                ViewModelBase.isInitialised = false;

                //ILogger : Allows MessageBoxs to be shown
                logger = (ILogger)this.iocProvider.GetTypeFromContainer <ILogger>();

                ServiceProvider.Add(typeof(ILogger), logger);

                //IMessageBoxService : Allows MessageBoxs to be shown
                IMessageBoxService messageBoxService =
                    (IMessageBoxService)this.iocProvider.GetTypeFromContainer <IMessageBoxService>();

                ServiceProvider.Add(typeof(IMessageBoxService), messageBoxService);

                //IOpenFileService : Allows Opening of files
                IOpenFileService openFileService =
                    (IOpenFileService)this.iocProvider.GetTypeFromContainer <IOpenFileService>();
                ServiceProvider.Add(typeof(IOpenFileService), openFileService);

                //ISaveFileService : Allows Saving of files
                ISaveFileService saveFileService =
                    (ISaveFileService)this.iocProvider.GetTypeFromContainer <ISaveFileService>();
                ServiceProvider.Add(typeof(ISaveFileService), saveFileService);

                //IUIVisualizerService : Allows popup management
                IUIVisualizerService uiVisualizerService =
                    (IUIVisualizerService)this.iocProvider.GetTypeFromContainer <IUIVisualizerService>();
                ServiceProvider.Add(typeof(IUIVisualizerService), uiVisualizerService);

                //call the callback delegate to setup IUIVisualizerService managed
                //windows
                if (SetupVisualizer != null)
                {
                    SetupVisualizer(uiVisualizerService);
                }

                ViewModelBase.isInitialised = true;
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }
Beispiel #26
0
        public void TestServiceCreatorCallback()
        {
            ServiceProvider provider = new ServiceProvider();

            provider.Add <ILog>(new ServiceCreatorCallback <ILog>(ServiceRequested));
            ILog log = provider.Get <ILog>();

            Assert.IsNotNull(log);
        }
Beispiel #27
0
 /// <summary>
 /// Init.
 /// </summary>
 static BaseViewModel()
 {
     // Register default services
     // TODO: Extension as in cinch (via Microsoft Unity IOC container) for testing, not needed now
     ServiceProvider.Add(typeof(IUIVisualizerService), new UIVisualizerService());
     ServiceProvider.Add(typeof(IOpenFileService), new OpenFileService());
     ServiceProvider.Add(typeof(ISaveFileService), new SaveFileService());
     ServiceProvider.Add(typeof(IMessageBoxService), new MessageBoxService());
 }
Beispiel #28
0
        public void OnGet_ItShouldResolveTheSameInstance()
        {
            //Arrange
            var serviceProvider   = new ServiceProvider();
            var vehicleRepository = new SqlRepository <Vehicle>();

            serviceProvider.Add(typeof(IRepository <Entity>), typeof(FakeSqlRepository <Entity>));
            serviceProvider.Add(typeof(IRepository <>), typeof(SqlRepository <>));
            serviceProvider.Add <IRepository <Vehicle> >(vehicleRepository);
            serviceProvider.Add <IHandler, Handler>();

            //Act
            var result     = serviceProvider.Get <IHandler>();
            var repository = serviceProvider.Get <IRepository <BaseEntity> >();
            var resolvedVehicleRepository = serviceProvider.Get <IRepository <Vehicle> >();

            //Assert
            Assert.Same(result.Repository, repository);
            Assert.Same(vehicleRepository, resolvedVehicleRepository);
        }
Beispiel #29
0
        private async Task OpenChannel(int port, string hostId)
        {
            var cacheContextAccessor = new CacheContextAccessor();
            var cache = new Cache(cacheContextAccessor);
            var namedDependencyProvider = new NamedCacheDependencyProvider();
            var contexts = new Dictionary <int, ApplicationContext>();
            var services = new ServiceProvider(_services);

            services.Add(typeof(ISourceTextService), new SourceTextService(cache));

            // This fixes the mono incompatibility but ties it to ipv4 connections
            var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, port));
            listenSocket.Listen(10);

            Console.WriteLine("Listening on port {0}", port);

            for (; ;)
            {
                var acceptSocket = await AcceptAsync(listenSocket);

                Console.WriteLine("Client accepted {0}", acceptSocket.LocalEndPoint);

                var stream     = new NetworkStream(acceptSocket);
                var queue      = new ProcessingQueue(stream);
                var connection = new ConnectionContext(
                    contexts,
                    services,
                    cache,
                    cacheContextAccessor,
                    namedDependencyProvider,
                    queue,
                    hostId);

                queue.OnReceive += message =>
                {
                    // Enumerates all project contexts and return them to the
                    // sender
                    if (message.MessageType == "EnumerateProjectContexts")
                    {
                        WriteProjectContexts(queue, contexts);
                    }
                    else
                    {
                        // Otherwise it's a context specific message
                        connection.OnReceive(message);
                    }
                };

                queue.Start();
            }
        }
        public void AddTest()
        {
            const string targetString = "This is a test";

            ServiceProvider sp = new ServiceProvider();

            sp.Add(typeof(string), targetString);

            var result = sp.Resolve <string>();

            Assert.AreEqual(targetString, result);
        }
        public void OnGet_ItShouldResolveType()
        {
            //Arrange
            var serviceProvider = new ServiceProvider();
            var parts           = new List <Type> {
                typeof(PartOne), typeof(PartTwo), typeof(PartTwo)
            };

            parts.ForEach(type => serviceProvider.Add(type));
            serviceProvider.Add <IPart[]>(provider => parts.Select(p => (IPart)provider.Get(p)).ToArray());
            serviceProvider.Add <FuncTestClass>();
            serviceProvider.Add <TestPartClass>();

            //Act
            var result = serviceProvider.Get <FuncTestClass>();

            //Assert
            Assert.NotNull(result.Parts);
            Assert.Equal(3, result.Parts.Length);
            Assert.Single(result.Parts.Where(p => p is PartOne));
            Assert.Equal(2, result.Parts.Count(p => p is PartTwo));
        }
        public void InvalidCastTest()
        {
            object          obj = new object();
            ServiceProvider sp  = new ServiceProvider();

            sp.Add(typeof(IComparable), obj);

            var result = sp.Resolve <string>();

            Assert.AreEqual(null, result);

            sp.Resolve <IComparable>();
        }
Beispiel #33
0
        private async void DiscoverTests()
        {
            if (_appPath.Value == null)
            {
                throw new InvalidOperationException("The context must be initialized with a project.");
            }

            string  testCommand = null;
            Project project     = null;

            if (Project.TryGetProject(_appPath.Value, out project))
            {
                project.Commands.TryGetValue("test", out testCommand);
            }

            if (testCommand == null)
            {
                // No test command means no tests.
                Trace.TraceInformation("[ApplicationContext]: OnTransmit(DiscoverTests)");
                OnTransmit(new Message
                {
                    ContextId   = Id,
                    MessageType = "TestDiscovery.Response",
                });

                return;
            }

            var testServices = new ServiceProvider(_hostServices);

            testServices.Add(typeof(ITestDiscoverySink), new TestDiscoverySink(this));

            var args = new string[] { "test", "--list", "--designtime" };

            try
            {
                await ExecuteCommandWithServices(testServices, project, args);
            }
            catch
            {
                // For now we're not doing anything with these exceptions, we might want to report them
                // to VS.
            }

            Trace.TraceInformation("[ApplicationContext]: OnTransmit(DiscoverTests)");
            OnTransmit(new Message
            {
                ContextId   = Id,
                MessageType = "TestDiscovery.Response",
            });
        }
Beispiel #34
0
        /// <summary>
        /// Create a default ServiceProvider with the given settings.
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceProvider Create(IDictionary<string, string> settings, Action<ServiceProvider> configuration)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            var services = new ServiceProvider();
            DoCallback(settings, (service, implementation) => services.Add(service, implementation));
            configuration(services);
            return services;
        }
Beispiel #35
0
        private static void AddCodeGenerationServices(ServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            serviceProvider.Add(typeof(IApplicationEnvironment), PlatformServices.Default.Application);
            serviceProvider.Add(typeof(IRuntimeEnvironment), PlatformServices.Default.Runtime);
            serviceProvider.Add(typeof(IAssemblyLoadContextAccessor), PlatformServices.Default.AssemblyLoadContextAccessor);
            serviceProvider.Add(typeof(IAssemblyLoaderContainer), PlatformServices.Default.AssemblyLoaderContainer);
            serviceProvider.Add(typeof(ILibraryManager), PlatformServices.Default.LibraryManager);
            serviceProvider.Add(typeof(ILibraryExporter), CompilationServices.Default.LibraryExporter);
            serviceProvider.Add(typeof(ICompilerOptionsProvider), CompilationServices.Default.CompilerOptionsProvider);

            //Ordering of services is important here
            serviceProvider.Add(typeof(ILogger), new ConsoleLogger());
            serviceProvider.Add(typeof(IFilesLocator), new FilesLocator());

            serviceProvider.AddServiceWithDependencies<ICodeGeneratorAssemblyProvider, DefaultCodeGeneratorAssemblyProvider>();
            serviceProvider.AddServiceWithDependencies<ICodeGeneratorLocator, CodeGeneratorsLocator>();

            serviceProvider.AddServiceWithDependencies<ICompilationService, RoslynCompilationService>();
            serviceProvider.AddServiceWithDependencies<ITemplating, RazorTemplating>();

            serviceProvider.AddServiceWithDependencies<IPackageInstaller, PackageInstaller>();

            serviceProvider.AddServiceWithDependencies<IModelTypesLocator, ModelTypesLocator>();
            serviceProvider.AddServiceWithDependencies<ICodeGeneratorActionsService, CodeGeneratorActionsService>();
            serviceProvider.AddServiceWithDependencies<IDbContextEditorServices, DbContextEditorServices>();
            serviceProvider.AddServiceWithDependencies<IEntityFrameworkService, EntityFrameworkServices>();
        }
Beispiel #36
0
 public static ServiceProvider Create()
 {
     var services = new ServiceProvider();
     DoCallback((service, implementation) => services.Add(service, implementation));
     return services;
 }