[.Net Core学习六]Startup详解

新建立的Core项目生成的Startup文件

[.Net Core学习六]Startup详解_第1张图片

从结构上看 共分为四个部分 

1.构造函数 Startup  Core的核心是依赖注入  所以要有构造函数进行注入 

2.承载注入实现的对象 IConfiguration

3.添加服务的方法 ConfigureServices

4.配置HTTP请求管道的方法 Configure

 

一二部分一般定义3个依赖注入

       //环境信息
        private readonly IHostingEnvironment _env;
        //获取配置信息使用 GetSection
        private readonly IConfiguration _config;
        //Log记录接口
        private readonly ILoggerFactory _loggerFactory;
        public MyStartup(IHostingEnvironment env, IConfiguration config,
        ILoggerFactory loggerFactory)
        {
            _env = env;
            _config = config;
            _loggerFactory = loggerFactory;
        }

ConfigureServices调用在Configure之前

ConfigureServices

这个方法为应用程序添加服务

例如

添加Service和Iservice注入

 services.AddScoped();

添加mongodb连接

    services.Configure(
Configuration.GetSection(nameof(BookstoreDatabaseSettings)));

添加EF连接

  services.AddDbContext(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));

添加Cookie策略

 services.Configure(options =>
            {
                // 此lambda确定给定请求是否需要非必需cookie的用户同意。
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

Startup的调用

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup();
    }

Main 用过控制台和windows程序的都知道这是主入口

CreateWebHostBuilder直接将Startup绑定到WebHost上 这里的Startup可以修改成自己写的Startup

 

无Startup文件

   public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
     WebHost.CreateDefaultBuilder(args)
         .ConfigureAppConfiguration((hostingContext, config) =>
         {
         })
         .ConfigureServices(services =>
         {
         })
         .Configure(app =>
         {
             var loggerFactory = app.ApplicationServices
                 .GetRequiredService();
             var logger = loggerFactory.CreateLogger();
             var env = app.ApplicationServices.GetRequiredService();
             var config = app.ApplicationServices.GetRequiredService();

             logger.LogInformation("Logged in Configure");

             if (env.IsDevelopment())
             {
             }
             else
             {
             }

             var configValue = config["subsection:suboption1"];
         });

这种方式可以不调用Startup直接将配置放在Program内完成 

当然这种方式并不推荐 可维护性并不好  适当了解一些就好

使用 Startup 筛选器扩展 Startup

定义中间件

public class RequestSetOptionsMiddleware
    {
        private readonly RequestDelegate _next;
        private IOptions _injectedOptions;

        public RequestSetOptionsMiddleware(
            RequestDelegate next, IOptions injectedOptions)
        {
            _next = next;
            _injectedOptions = injectedOptions;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            Console.WriteLine("RequestSetOptionsMiddleware.Invoke");

            var option = httpContext.Request.Query["option"];

            if (!string.IsNullOrWhiteSpace(option))
            {
                _injectedOptions.Value.Option = WebUtility.HtmlEncode(option);
            }

            await _next(httpContext);
        }
    }

使用中间件

 public class RequestSetOptionsStartupFilter : IStartupFilter
    {
        public Action Configure(Action next)
        {
            return builder =>
            {
                builder.UseMiddleware();
                next(builder);
            };
        }
    }

添加到主机

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .ConfigureServices(services =>
            {
                services.AddTransient();
            })
            .UseStartup();

 

你可能感兴趣的:(Core)