Skip to content

Commit

Permalink
Remove Startup class to work only Program.cs class (#19)
Browse files Browse the repository at this point in the history
* Remove Startup class

* Remove deprecated packages from API Project ans fix API Startup from Docker

* Remove unused code
  • Loading branch information
vanderlan authored Sep 28, 2023
1 parent 12e9701 commit d30fcff
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 134 deletions.
4 changes: 4 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine AS build

ENV ASPNETCORE_URLS=http://+:80

WORKDIR /app

COPY . .

EXPOSE 80

RUN dotnet restore "Orion.Api/Orion.Api.csproj"
RUN dotnet publish "Orion.Api/Orion.Api.csproj" -c Release -o /out

Expand Down
72 changes: 11 additions & 61 deletions Orion.Api/Startup.cs → Orion.Api/Bootstraper.cs
Original file line number Diff line number Diff line change
@@ -1,50 +1,30 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using AutoMapper;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Orion.Api.AutoMapper.Config;
using Orion.Api.Jwt;
using Orion.Api.Middleware;
using Orion.Api.Validators;
using Orion.Ioc.Dependencies;
using System.Globalization;
using System.Text;

namespace Orion.Api
{
public class Startup
public static class Bootstraper
{
private readonly ILoggerFactory _loggerFactory;
private readonly IWebHostEnvironment _env;
private IConfiguration Configuration { get; set; }

public Startup(IConfiguration configuration, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
_env = env;
Configuration = configuration;
}

public void ConfigureServices(IServiceCollection services)
public static void ConfigureServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddCors();

ConfigureAuthentication(services);
ConfigureAuthentication(services, configuration);

services.AddControllers();

Expand All @@ -62,7 +42,7 @@ public void ConfigureServices(IServiceCollection services)
ConfigureApiVersioning(services);

services.AddDomainServices();
services.AddAutoMapper(typeof(Startup));

ConfigureMapper(services);
}

Expand Down Expand Up @@ -122,21 +102,10 @@ private static void ConfigureSwagger(IServiceCollection services)
});
}

private void ConfigureAuthentication(IServiceCollection services)
private static void ConfigureAuthentication(IServiceCollection services, IConfiguration configuration)
{
var jwtConfiguration = Configuration.GetSection("JwtConfiguration").Get<JwtConfiguration>();

services.AddIdentity<IdentityUser, IdentityRole>(
option =>
{
option.Password.RequireDigit = false;
option.Password.RequiredLength = 6;
option.Password.RequireNonAlphanumeric = false;
option.Password.RequireUppercase = false;
option.Password.RequireLowercase = false;
}
).AddDefaultTokenProviders();

var jwtConfiguration = configuration.GetSection("JwtConfiguration").Get<JwtConfiguration>();

services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
Expand All @@ -157,7 +126,7 @@ private void ConfigureAuthentication(IServiceCollection services)
});
}

public void ConfigureMapper(IServiceCollection services)
public static void ConfigureMapper(IServiceCollection services)
{
var mappingConfig = new MapperConfiguration(mc =>
{
Expand All @@ -168,20 +137,8 @@ public void ConfigureMapper(IServiceCollection services)
services.AddScoped(_ => mappingConfig.CreateMapper());
}

public void Configure(IApplicationBuilder app, IHostEnvironment env)
public static void ConfigureApp(this IApplicationBuilder app)
{
var logger = _loggerFactory.CreateLogger<Startup>();

//ENVIRONMENT
if (env.IsDevelopment())
{
logger.LogInformation("Development environment");
}
else
{
logger.LogInformation("Environment: {Env}", _env.EnvironmentName);
app.UseHsts();
}
app.UseMiddleware<OrionMiddleware>();

//SWAGGER
Expand All @@ -201,13 +158,6 @@ public void Configure(IApplicationBuilder app, IHostEnvironment env)

app.UseHealthChecks("/health-check");

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();
app.UseRouting();

app.UseAuthentication();
Expand Down
15 changes: 6 additions & 9 deletions Orion.Api/Orion.Api.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<AssemblyName>Orion.Api</AssemblyName>
<UserSecretsId>7401dc57-e892-498d-a628-03091ec95c6a</UserSecretsId>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>

Expand All @@ -15,22 +16,14 @@
</PackageReference>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.11" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Server.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="5.0.17" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Routing.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="7.0.11" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.10" />
<PackageReference Include="NLog" Version="5.2.4" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.4" />
Expand All @@ -44,6 +37,10 @@
<ProjectReference Include="..\Orion.Resources\Orion.Resources.csproj" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Orion.Test" />
</ItemGroup>

<ItemGroup>
<Content Update="appsettings.Test.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
Expand Down
46 changes: 7 additions & 39 deletions Orion.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,43 +1,11 @@
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Web;
using Orion.Api;

namespace Orion.Api
{
public static class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
var builder = WebApplication.CreateBuilder(args);

try
{
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
LogManager.Shutdown();
}
}
builder.Services.ConfigureServices(builder.Configuration);

private static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://*:5000")
.UseStartup<Startup>()
.UseIISIntegration()
.ConfigureLogging((context, logging) =>
{
logging.ClearProviders();
logging.AddConsole();
}).UseNLog();
var app = builder.Build();

}
}
app.ConfigureApp();

app.Run();
Empty file.
1 change: 0 additions & 1 deletion Orion.Test/API/HealthCheckApiTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ public class HealthCheckApiTest: ApiTestInitializer
public async Task GetAsync_HealthCheck_ReturnsHealthy()
{
//arrange
Setup();
var successMessageService = "Healthy";

//act
Expand Down
68 changes: 46 additions & 22 deletions Orion.Test/Configuration/ApiTestInitializer.cs
Original file line number Diff line number Diff line change
@@ -1,40 +1,51 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Orion.Api.Models;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Orion.Api;
using Orion.Api.Models;

namespace Orion.Test.Configuration
{
public abstract class ApiTestInitializer : WebApplicationFactory<Startup>
public abstract class ApiTestInitializer : IDisposable
{
protected HttpClient Client;
protected string AuthToken;

public ApiTestInitializer()
{
protected readonly HttpClient Client;
protected readonly HttpClient AuthenticatedClient;
protected IServiceProvider ServiceProvider { get; private set; }

}

public void Setup()
public ApiTestInitializer()
{
var builder = new WebHostBuilder();

base.ConfigureWebHost(builder);

Client = Server.CreateClient();
var appFactory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.Test.json", optional: false, reloadOnChange: true)
.Build();

AuthUser();

Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);
builder
.UseConfiguration(config)
.ConfigureServices(services =>
{
});
});
ServiceProvider = appFactory.Services;
Client = appFactory.CreateClient();
AuthenticatedClient = appFactory.CreateClient();
}

public void AuthUser()
{
var result = Client.PostAsync("/api/Auth/Login", GetStringContent(new UserLoginModel { Email = "[email protected]", Password = "123" })).GetAwaiter().GetResult();
var result = Client.PostAsync("/api/Auth/Login", GetStringContent(
new UserLoginModel {
Email = "[email protected]",
Password = "123"
}))
.GetAwaiter().GetResult();

var content = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();

Expand All @@ -48,12 +59,25 @@ protected static StringContent GetStringContent(object obj)
return new StringContent(JsonConvert.SerializeObject(obj), Encoding.Default, "application/json");
}

protected override void ConfigureWebHost(IWebHostBuilder builder)
private bool _disposedValue = false;

protected virtual void Dispose(bool disposing)
{
builder.UseEnvironment("Test")
.UseStartup<Startup>();
if (!_disposedValue)
{
_disposedValue = true;
}
}

base.ConfigureWebHost(builder);
~ApiTestInitializer()
{
Dispose(false);
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
4 changes: 2 additions & 2 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ services:
context: .
dockerfile: Dockerfile
ports:
- "8080:5000"
container_name: orion-api
- "5010:80"
container_name: orion
networks:
- backend-network
networks:
Expand Down

0 comments on commit d30fcff

Please sign in to comment.