最初始的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
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(); });
}
主要是http处理管道配置和一些系统配置,参数如下:
IApplicationBuilder: 用于构建应用请求管道。通过IApplicationBuilder下的run方法传入管道处理方法。这是最常用方法,对于一个真实环境的应用基本上都需要比如权限验证、跨域、异常处理等。下面代码调用IApplicationBuilder.Run方法注册处理函数。拦截每个http请求,输出Hello World。 public void Configure(IApplicationBuilder app) { app.Run((context) => context.Response.WriteAsync("Hello World!")); }
IHostingEnvironment: 同构造参数
ILoggerFactory: 同构造参数
原文地址
转载于:https://www.cnblogs.com/ZkbFighting/p/10710755.html
