. NET Core 2.0 MVC initial Learning

Source: Internet
Author: User
Tags webhost

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 Iconfigur        ation Configuration {get; set;}        Public Studystartup () {}//<summary>//For obtaining configuration information///</summary>            <param name= "Configuration" ></param> public studystartup (iconfiguration configuration) {        Configuration = Configuration; } public IServiceProvider configureservices (iservicecollection services) {//inject MVC Ser Vices.            Addmvc ();          Add options  Services.            AddOptions (); Gets the configuration information services.            Configure<appsetting> (Configuration.getsection (nameof (appsetting))); Turn on session feature services. Addsession (Options ={options.            IdleTimeout = Timespan.fromminutes (30);            }); Constructs a default ServiceProvider processing object return services.        Buildserviceprovider (); } public void Configure (Iapplicationbuilder app, ihostingenvironment Environment, Iloggerfact            Ory loggerfactory, Ihttpcontextfactory httpcontextfactory, Diagnosticsource Diagnosticsource, Diagnosticlistener diagnosticlistener) {//The current environment is the development environment if (environment. Isdevelopment ()) {app.                Usebrowserlink (); App.            Usedeveloperexceptionpage (); } else {app.            Useexceptionhandler ("/home/error"); }//IMPORTANT: The registration of the session must precede USEMVC, because MVCUse the app inside.            Usesession (); Use the static file app in Webroot.            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) Related source Iwebhostbuilder Webhostbuilder = Webhost.createdefaultbuilder ( args); method parsing public static Iwebhostbuilder Createdefaultbuilder (string[] args) {return new Webhostbuilder ().      Usekestrel ()//specify Kestrel as the server to being used by the web host. . Usecontentroot (Directory.GetCurrentDirectory ())//Use the current directory as content and directory//configuration information processing. Configureappconfiguration ((Action<webhostbuildercontext, iconfigurationbuilder>) ((hostingContext, config) =              > {//Inject operating environment ihostingenvironment hostingenvironment = hostingcontext.hostingenvironment; Load configuration file CONFIG. Addjsonfile ("Appsettings.json", True, true). Addjsonfile (String. Format ("appsettings.{          0}.json ", (object) hostingenvironment.environmentname), True, true); Load the appropriate file according to the running environment if (hostingenvironment.isdevelopment ()) {Assembly Assembly = ASSEMBLY.L Oad (New AssemblyName (Hostingenvironment.applicationname)); if (assembly! = (assembly) null) CONFIG.            Addusersecrets (assembly, true); } config.            Addenvironmentvariables ();            if (args = = null) return; Config.      Addcommandline (args); }))//configuration log information. Configurelogging ((Action<webhostbuildercontext, iloggingbuilder>) ((hostingcontext, logging) = {log Ging.        Addconfiguration ((iconfiguration) hostingContext.Configuration.GetSection ("Logging")); Logging.        Addconsole (); Logging.      Adddebug (); }))      . Useiisintegration ()//Publish with IIS. Usedefaultserviceprovider (Action<webhostbuildercontext, serviceprovideroptions>) (context, options) = Options. Validatescopes = context. Hostingenvironment.isdevelopment ()));//using the default processing mechanism}

Even if need to use the parameter construction of startup, you need to configure the corresponding processing class in Configureappconfiguration

Request direction:

Initial: Run---configureservices-Configure

Configuration information is obtained:

<Controller>protected AppSetting ConfigInfo { get; set; }    //读取配置信息protected BaseController(IOptions<AppSetting> options) => ConfigInfo = options.Value;

DI injection

1. The Created DI injection is processed at 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

To turn on the session function:

<method --> ConfigureServices>    services.AddSession(options => {            options.IdleTimeout = TimeSpan.FromMinutes(30);//存储时长        });<method --> Configure >    // 重要: session的注册必须在UseMvc之前,因为MVC里面要用         app.UseSession();

. NET Core 2.0 MVC initial learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.