Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

best pratice how to organize Startup file .net core 2.0

$
0
0

Hello could you help me I would like know how to organise the file Startup.cs to dotnet core 2.0.3

I used 

IIS : v6.1
Security : Microsoft.AspNetCore.Authentication.JwtBearer v2.0.1
DataAccess : Microsoft.EntityFrameworkCore v2.0.1
I18N : Razor MVC
Logging : log4net v2.0.8
Cache : IMemoryCache
Documentation: Swashbuckle.AspNetCore v1.1.0
GenerateHtml : RazorLight

  1. ConfigureIIS
  2. ConfigureSecurity
  3. ConfigureDatabase
  4. ConfigureFormatter
  5. ConfigureI18N
  6. ConfigureAllActionFilterAttribute
  7. ConfigureRepositories
  8. ConfigureBusiness
  9. ConfigureLogging
  10. ConfigureCache
  11. ConfigureDocumentation
  12. ConfigurationRazorLight 
namespace XXXWebPortal.API
{
    using System;
    using System.Text;
    using XXXPortal.FileManagers;
    using XXXPortal.FileManagers.Contracts;
    using XXXPortal.UserManagers;
    using XXXPortal.UserManagers.Contracts;
    using XXXWebPortal.API.Attributes;
    using XXXWebPortal.API.Extensions;
    using XXXWebPortal.API.Services;
    using XXXPortal.YYYYdocs.Contracts;
    using XXXPortal.YYYYdocs.Impl;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.IdentityModel.Tokens;
    using XXXPortal.Database;
    using XXXPortal.MailManagers.Contracts;
    using XXXPortal.MailManagers;
    using XXXPortal.Mails.Contracts;
    using XXXPortal.Mails.Impl;
    using XXXPortal.Encryptions.Contracts;
    using XXXPortal.Encryptions.Impl;
    using XXXWebPortal.API.Authorization;
    using XXXPortal.SecurityManagers.Contracts;
    using XXXPortal.SecurityManagers;
    using XXXPortal.Securities.Contracts;
    using XXXPortal.Securities.Impl;
    using XXXPortal.DataAccess.Contracts;
    using XXXPortal.DataAccess.Impl;
    using XXXPortal.WebPortals.Contracts;
    using XXXPortal.WebPortals.Impl;
    using XXXPortal.QQQQQQPortals.Contracts;
    using XXXPortal.QQQQQQPortals.Impl;
    using Microsoft.AspNetCore.Mvc.Razor;
    using System.Collections.Generic;
    using System.Globalization;
    using Microsoft.AspNetCore.Localization;
    using Microsoft.AspNetCore.Http;
    using XXXPortal.GenerateDocumentsManagers.Contracts;
    using XXXPortal.GenerateDocumentsManagers;
    using Microsoft.Extensions.Logging;
    using XXXPortal.Core.Log;
    using XXXPortal.Core.Log.Contracts;
    using XXXPortal.DataManagers.Contracts;
    using XXXPortal.DataManagers;
    using XXXWebPortal.API.Formatters;
    using Microsoft.Net.Http.Headers;
    using Swashbuckle.AspNetCore.Swagger;

    public class Startup
    {
        private const string enUSCulture = "en-US";

        public IConfiguration Configuration { get; }
        public IHostingEnvironment Environment { get; }
        private IServiceCollection Services { get; set; }

        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            Environment = env;

            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            this.ConfigureIIS(services);
            this.ConfigureSecurity(services);
            this.ConfigureDatabase(services);

            var csvFormatterOptions = new CsvFormatterOptions();
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMvc(
                options =>
                {
                    options.InputFormatters.Add(new CsvInputFormatter(csvFormatterOptions));
                    options.OutputFormatters.Add(new CsvOutputFormatter(csvFormatterOptions));
                    options.FormatterMappings.SetMediaTypeMappingForFormat("csv", MediaTypeHeaderValue.Parse("text/csv"));
                })
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization();

            services.AddScoped<LogActionAttribute>();

            this.ConfigureRepositories(services);
            this.ConfigureBusiness(services);

            this.ConfigureLogging(services);
            this.ConfigureCache(services);
            this.ConfigureDocumentation(services);

           /*var engine = new RazorLightEngineBuilder()
              .UseFilesystemProject(path)
              .UseMemoryCachingProvider()
              .Build();*/
			
            Services = services;
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime, ILoggerFactory loggerFactory)
        {
            appLifetime.ApplicationStarted.Register(OnStarted);
            appLifetime.ApplicationStopping.Register(OnStopping);
            appLifetime.ApplicationStopped.Register(OnStopped);

            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();

            app.UseCors(builder =>
           {
               builder.AllowAnyHeader();
               builder.AllowAnyMethod();
               builder.AllowAnyOrigin();
               builder.AllowCredentials();
           });

            app.UseHTTPLogging();

            app.UseAuthentication();
            app.UseApiKeySecurity();
            app.UseTest();

            app.UseErrorLogging();

            this.UseRequestLocalization(app);//app.UseRequestLocalization();

            if (!env.IsProduction())
            {
                app.UseDocumentation();
                UseViewAllRegisteredServices(app, env);
            }

            app.UseMvc();
        }

        private void OnStarted()
        {
            Log("XXX API has fully started");
        }

        private void OnStopping()
        {
            Log("XXX API is performing a graceful shutdown");
        }

        private void OnStopped()
        { 
            Log("Shutdown blocks until this event completes");
        }

        private void ConfigureIIS(IServiceCollection services)
        {
            services.Configure<IISOptions>(options =>
            {
                options.AutomaticAuthentication = false;
            });
        }

        private void ConfigureSecurity(IServiceCollection services)
        {
            services
                .AddAuthentication(options =>
                {
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(jwtOptions =>
                {
                    jwtOptions.IncludeErrorDetails = true;
                    jwtOptions.RequireHttpsMetadata = Environment.IsProduction();

                    jwtOptions.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue<string>("Settings:JwtSymmetricKey"))),

                        ValidateIssuer = true,
                        ValidIssuer = "XXXWebPortal",

                        ValidateAudience = true,
                        ValidAudience = "XXXWebPortal",

                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero
                    };
                });

            services.AddAuthorization();
        }

        private void ConfigureDatabase(IServiceCollection services)
        {
            services.AddDbContext<XXXContext>(options =>
            {
                //options.UseLoggerFactory(MyLoggerFactory); // Warning: Do not create a new ILoggerFactory instance each time
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });
        }

        private void ConfigureRepositories(IServiceCollection services)
        {
            services.AddScoped<IEncryptionRepository, EncryptionRepository>();
            services.AddScoped<IImpersonationContextRepository, ImpersonationContextRepository>();

            services.AddSingleton<IWebPortalRepository, WebPortalRepository>();

            services.AddScoped<IRafRepository, RafRepository>();
            services.AddScoped<IClassificationRepository, ClassificationRepository>();
            services.AddScoped<IRequirementRepository, RequirementRepository>();

            services.AddScoped<IMailRepository, MailRepository>();

            services.AddScoped<IAAAAARepository, AAAAARepository>();
            services.AddScoped<XXXPortal.SharePoint.Contracts.IDocumentRepository, XXXPortal.SharePoint.Impl.DocumentRepository>();
            services.AddScoped<XXXPortal.DataAccess.Contracts.IDocumentRepository, XXXPortal.DataAccess.Impl.DocumentRepository>();

            services.AddScoped<IBBBBBBBPortalRepository, BBBBBBBPortalRepository>();
            services.AddScoped<IRafUserDetailsRepository, RafUserDetailsRepository>();

        }

        private void ConfigureBusiness(IServiceCollection services)
        {
            services.AddTransient<ITokenService, TokenService>();

            services.AddSingleton<ILogBusiness, LogBusiness>();

            services.AddScoped<ISharePointFileManager, SharePointFileManager>();
            services.AddScoped<IAAAAAFileManager, AAAAAFileManager>();

            services.AddScoped<IXXXUserManager, XXXUserManager>();
            services.AddScoped<IWAUserManager, WAUserManager>();
            services.AddScoped<IUserManager, UserManager>();

            services.AddScoped<IMailerManager, MailerManager>();
            services.AddScoped<IMailManager, MailManager>();

            services.AddScoped<IImpersonationManager, ImpersonationManager>();

            services.AddScoped<IGenerateDocumentManager, GenerateDocumentManager>();

            services.AddScoped<IClassificationManager, ClassificationManager>();
            services.AddScoped<IRequirementManager, RequirementManager>();
            services.AddScoped<IDocumentManager, DocumentManager>();

            services.AddScoped<IRafManager, RafManager>();
            services.AddScoped<IRafUserDetailsManager, RafUserDetailsManager>();


            // services.AddTransient<IMyClass, MyClass>(); // Lifetime service
            // services.AddScoped<IMyClass, MyClass>();    // Request scoped service
            // services.AddSingleton<IMyClass, MyClass>(); // Singleton service
        }

        private void ConfigureLogging(IServiceCollection services)
        {
            services.AddLogging(builder => builder
                 .AddLog4Net()
                 .AddConsole()
                 .AddDebug()
                 //.AddFilter((provider, category, logLevel) =>
                 //{
                 //    if (provider == "XXXWebPortal.API.Log4NetProvider" && category == "XXXPortal.Core.Log.LogApplication")
                 //        return true;

                 //    return false;
                 //}));
            //.AddFilter("System", LogLevel.Critical) // Rule for all providers
            //.AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Critical) // Rule only for debug provider
            .AddConfiguration(Configuration.GetSection("Logging"))); // Would add rules from IConfiguration, overriding default rules added above
        }

        private void ConfigureCache(IServiceCollection services)
        {
            services.AddMemoryCache();
        }

        private void ConfigureDocumentation(IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Documentation XXX Web Portal",
                    Description = "Specification TTTTTTTT API",
                    Contact = new Contact { Name = "TEAM IT", Email = Configuration["XXXPortalMailboxes:XXX.BAL.IT.Team"] },
                });
            });
        }

        private void UseRequestLocalization(IApplicationBuilder app)
        {
            var supportedCultures = new List<CultureInfo>
            {
                new CultureInfo("fr"),
                new CultureInfo(enUSCulture)
            };

            var localizationOptions = new RequestLocalizationOptions()
            {
                DefaultRequestCulture = new RequestCulture(culture: enUSCulture, uiCulture: enUSCulture),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            };

            app.UseRequestLocalization(localizationOptions);
        }

        private void UseViewAllRegisteredServices(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.Map("/allservices", builder => builder.Run(async context =>
            {
                var sb = new StringBuilder();

                sb.AppendLine($"({Configuration.GetConnectionString("DefaultConnection")}) <h1>BDD</h1>");

                sb.AppendLine($"({env.IsDevelopment()}) <h1>IsDevelopment</h1>");
                sb.AppendLine($"({env.IsEnvironment("REC")}) <h1>IsREC</h1>");
                sb.AppendLine($"({env.IsStaging()}) <h1>IsStaging</h1>");
                sb.AppendLine($"({env.IsProduction()}) <h1>IsProduction</h1>");

                sb.AppendLine(string.Empty);
                sb.AppendLine($"({env.EnvironmentName}) <h1>All Services</h1>");
                sb.Append("<table><thead>");
                sb.Append("<tr><th>Type</th><th>Lifetime</th><th>Instance</th></tr>");
                sb.Append("</thead><tbody>");
                foreach (var svc in Services)
                {
                    sb.Append("<tr>");
                    sb.Append($"<td>{svc.ServiceType.FullName}</td>");
                    sb.Append($"<td>{svc.Lifetime}</td>");
                    sb.Append($"<td>{svc.ImplementationType?.FullName}</td>");
                    sb.Append("</tr>");
                }
                sb.Append("</tbody></table>");
                await context.Response.WriteAsync(sb.ToString());
            }));
        }

        private void Log(string message)
        {
            string userName = UsersKeys.XXX_API_PORTAL;
            string uniqueIdHttpRequest;

            userName = userName.PadRight(18, ' ');
            uniqueIdHttpRequest = new String(' ', 22);

            LogApplication.Log.Debug($"{userName} {uniqueIdHttpRequest} {message}");
        }
    }
}


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>