예제 #1
0
        /// <summary>
        /// Builds the required services and an <see cref="IConsole"/> which hosts a web application.
        /// </summary>
        public IConsole Build()
        {
            if (_consoleBuilt)
            {
                throw new InvalidOperationException("This console application has already been built.");
            }
            _consoleBuilt = true;

            var services               = BuildCommonServices();
            var applicationServices    = services.Clone();
            var consoleServiceProvider = GetProviderFromFactory(services);

            var service = new ConsoleApplication(applicationServices, consoleServiceProvider, _config);

            try
            {
                service.Initialize();

                return(service);
            }
            catch
            {
                // Dispose the host if there's a failure to initialize, this should clean up
                // will dispose services that were constructed until the exception was thrown
                service.Dispose();
                throw;
            }

            IServiceProvider GetProviderFromFactory(IServiceCollection collection)
            {
                var provider = collection.BuildServiceProvider();
                var factory  = provider.GetService <IServiceProviderFactory <IServiceCollection> >();

                if (factory != null)
                {
                    using (provider)
                    {
                        return(factory.CreateServiceProvider(factory.CreateBuilder(collection)));
                    }
                }

                return(provider);
            }
        }
예제 #2
0
 public override void Dispose()
 {
     ApplicationContext.DisposeIfDisposable();
     _application.Dispose();
 }