关于Core里的 StartUp里的方法的理解。

it2026-08-30  1

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); } }

最初始的StartUp里的方法就是标红的这几个,一个构造函数一个属性和2个方法。

对于一个ASP.NET Core 程序而言,Startup Class 是必须的。ASP.NET Core在程序启动时会从assemblies中找到名字叫Startup的类,如果存在多个名为Startup的类,则会先找到项目根名称空间下的Startup类。

Startup必须定义Configure方法,而configureServices方法则是可选的,方法会在程序第一次启动时被调用,类似传统的ASP.NET MVC的路由和应用程序状态均可在Startup中配置,也可以在此安装所需中间件等等。

ConfigureServices方法在Configure方法前调用,它是一个可选的方法可在configureServices里依赖注入接口或一些全局的框架,比如EntityFramework、MVC等。

Configure方法用于每次http请求的处理,

Startup 类的 执行顺序:构造 -> configureServices->configure

ConfigureServices:

主要实现了依赖注入(DI)的配置,方法参数如下:

IServiceCollection:整个ASP.NET Core 默认带有依赖注入(DI),IServiceCollection是依赖注入的容器,首先创建一个类(Foo)和接口(IFoo),代码清单如下:

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApplication1 { public interface IFoo { string GetFoo(); } } using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApplication1 { public class Foo : IFoo { public string GetFoo() { return "foo"; } } }

在ConfigureServices 中接口和实现注入至容器  

public void ConfigureServices(IServiceCollection services) { services.AddTransient<IFoo, Foo>(); }

 

如果想在每次Http请求后都使用IFoo的GetFoo()方法来处理,上面讲到可以在Configure方法中注册函数,在注册过程中由于使用了依赖注入(DI),因此可以直接通过RequestServices.GetRequiredService<IFoo>()泛型方法将IFoo对象在容器中取出。

app.Run((context) => { var str = context.RequestServices.GetRequiredService<IFoo>().GetFoo(); return context.Response.WriteAsync(str); });

除了自己的接口外,还支持通过扩展方法添加更多的注入方法,比如EntityFramework、mvc框架都实现自己的添加方法。

public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc(); // Add application services. services.AddTransient<IFoo, Foo>();

services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); var conn = Configuration.GetSection("ConnectionStrings"); string efconn = conn["acc_miniehub"]; string sbconn = conn["acc_sb"];

services.AddDbContext<OMSECData.Acc_OmsContext> ( options => options.UseSqlServer(efconn) ); //配置CAP services.AddCap(x => { x.UseEntityFramework<OMSECData.Acc_OmsContext>(); x.UseAzureServiceBus(sb => { sb.ConnectionString = sbconn; sb.TopicPath = "oms.q"; }); //启用操作面板 x.UseDashboard(); });

}

  

Configure方法

主要是http处理管道配置和一些系统配置,参数如下:

IApplicationBuilder: 用于构建应用请求管道。通过IApplicationBuilder下的run方法传入管道处理方法。这是最常用方法,对于一个真实环境的应用基本上都需要比如权限验证、跨域、异常处理等。下面代码调用IApplicationBuilder.Run方法注册处理函数。拦截每个http请求,输出Hello World。 public void Configure(IApplicationBuilder app) { app.Run((context) => context.Response.WriteAsync("Hello World!")); }

  

IHostingEnvironment: 同构造参数

ILoggerFactory: 同构造参数

原文地址

ASP.NET CORE读取appsettings.json的配置

转载于:https://www.cnblogs.com/ZkbFighting/p/10710755.html

最新回复(0)