// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Microsoft.AspNetCore.Hosting
{
public static class WebHostBuilderExtensions
{
///
/// Specify the startup method to be used to configure the web application.
///
/// The to configure.
/// The delegate that configures the .
/// The .
public static IWebHostBuilder Configure(this IWebHostBuilder hostBuilder, Action configureApp)
{
if (configureApp == null)
{
throw new ArgumentNullException(nameof(configureApp));
}
var startupAssemblyName = configureApp.GetMethodInfo().DeclaringType.GetTypeInfo().Assembly.GetName().Name;
return hostBuilder.UseSetting(WebHostDefaults.ApplicationKey, startupAssemblyName)
.ConfigureServices(services =>
{
services.AddSingleton(sp =>
{
return new DelegateStartup(sp.GetRequiredService>(), configureApp);
});
});
}
///
/// Specify the startup type to be used by the web host.
///
/// The to configure.
/// The to be used.
/// The .
public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, Type startupType)
{
var startupAssemblyName = startupType.GetTypeInfo().Assembly.GetName().Name;
return hostBuilder.UseSetting(WebHostDefaults.ApplicationKey, startupAssemblyName)
.ConfigureServices(services =>
{
if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
{
services.AddSingleton(typeof(IStartup), startupType);
}
else
{
services.AddSingleton(typeof(IStartup), sp =>
{
var hostingEnvironment = sp.GetRequiredService();
return new ConventionBasedStartup(StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName));
});
}
});
}
///
/// Specify the startup type to be used by the web host.
///
/// The to configure.
/// The type containing the startup methods for the application.
/// The .
public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder) where TStartup : class
{
return hostBuilder.UseStartup(typeof(TStartup));
}
///
/// Configures the default service provider
///
/// The to configure.
/// A callback used to configure the for the default .
/// The .
public static IWebHostBuilder UseDefaultServiceProvider(this IWebHostBuilder hostBuilder, Action configure)
{
return hostBuilder.ConfigureServices(services =>
{
var options = new ServiceProviderOptions();
configure(options);
services.Replace(ServiceDescriptor.Singleton>(new DefaultServiceProviderFactory(options)));
});
}
}
}