.net core 2.0 mvc 初步学习
程序员文章站
2022-07-05 17:00:25
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();
上一篇: 【转】 Linux下软链接与硬链接的区别
下一篇: 转:VB中的API详解