mvc_study StudyStartup Program code explain construction 即若需要使用startup的有參構造,則需要在configureappconfiguration中進行配置相應處理類 請求走向: 初始:Run --> ConfigureServices ...
mvc_study
StudyStartup
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Web.Study.ConfigModel;
using Web.Study.MonsterInterface;
namespace Web.Study.InhertStartup
{
public class StudyStartup
{
protected IConfiguration Configuration { get; set; }
public StudyStartup()
{
}
/// <summary>
/// 用於獲取配置信息
/// </summary>
/// <param name="configuration"></param>
public StudyStartup(IConfiguration configuration)
{
Configuration = configuration;
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//註入mvc
services.AddMvc();
//添加Options
services.AddOptions();
//獲取配置信息
services.Configure<AppSetting>(Configuration.GetSection(nameof(AppSetting)));
//開啟Session功能
services.AddSession(options ={
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
//構建一個預設的serviceProvider處理對象
return services.BuildServiceProvider();
}
public void Configure(IApplicationBuilder app,
IHostingEnvironment environment,
ILoggerFactory loggerFactory,
IHttpContextFactory httpContextFactory,
DiagnosticSource diagnosticSource,
DiagnosticListener diagnosticListener)
{
//當前環境為開發環境
if (environment.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
// 重要: session的註冊必須在UseMvc之前,因為MVC裡面要用
app.UseSession();
//使用webroot中的靜態文件
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Program
public static IWebHost BuildWebHost<T>(string[] args) where T:class
{
IWebHostBuilder webHostBuilder = WebHost.CreateDefaultBuilder(args);
IWebHostBuilder hostBuilder = webHostBuilder.UseStartup<T>();
IWebHost webHost = hostBuilder.Build();
return webHost;
}
code explain
construction
public StudyStartup(IConfiguration configuration)
相關源碼
IWebHostBuilder webHostBuilder = WebHost.CreateDefaultBuilder(args);
方法解析
public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
return new WebHostBuilder()
.UseKestrel()//Specify Kestrel as the server to be used by the web host.
.UseContentRoot(Directory.GetCurrentDirectory())//採用當前目錄作為內容跟目錄
//配置信息處理
.ConfigureAppConfiguration((Action<WebHostBuilderContext, IConfigurationBuilder>) ((hostingContext, config) =>
{
//註入運行環境
IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
//載入配置文件
config.AddJsonFile("appsettings.json", true, true).AddJsonFile(string.Format("appsettings.{0}.json", (object) hostingEnvironment.EnvironmentName), true, true);
//根據運行環境載入相應文件
if (hostingEnvironment.IsDevelopment())
{
Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
if (assembly != (Assembly) null)
config.AddUserSecrets(assembly, true);
}
config.AddEnvironmentVariables();
if (args == null)
return;
config.AddCommandLine(args);
}))
//配置日誌信息
.ConfigureLogging((Action<WebHostBuilderContext, ILoggingBuilder>) ((hostingContext, logging) =>
{
logging.AddConfiguration((IConfiguration) hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
}))
.UseIISIntegration()//採用IIS進行發佈
.UseDefaultServiceProvider((Action<WebHostBuilderContext, ServiceProviderOptions>) ((context, options) => options.ValidateScopes = context.HostingEnvironment.IsDevelopment()));//採用預設的處理機制
}
即若需要使用startup的有參構造,則需要在configureappconfiguration中進行配置相應處理類
請求走向:
初始:Run --> ConfigureServices --> Configure
配置信息的獲取:
<Controller>
protected AppSetting ConfigInfo { get; set; }
//讀取配置信息
protected BaseController(IOptions<AppSetting> options) => ConfigInfo = options.Value;
DI註入
1.創建的DI註入在ConfigureServices進行處理
註入方式:
services.AddSingleton(u => new MonsterDIController(new GuestDal()));//指定控制器進行註入
services.AddSingleton<IDal,DefaultDal>();//統一註入 全局共用一個
services.AddTransient<IDal, DefaultDal>();//統一註入 每次使用都不一樣,不同的類或不同的方法使用都不一樣
services.AddScoped<IDal, EmptyDal>();//統一註入 一次請求共用一個對象
註:
當對同一類型構造傳入不同類型對象的註入時,
不考慮註入類型或範圍
已最終註入類型為傳入對象創建實例
例如:
<Controller>
protected IDal Dal { get; set; }
public MonsterDIController(IDal dal)
{
this.Dal = dal;
}
<ConfigureServices>
如上述一致
<Result>
最終創建實例時,會傳入EmptyDal
開啟Session功能:
<method --> ConfigureServices>
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(30);//存儲時長
});
<method --> Configure >
// 重要: session的註冊必須在UseMvc之前,因為MVC裡面要用
app.UseSession();