Anto Subash.

This is the part 11 of the series: .NET Microservice with ABP

Posts in the Series

Part 1. Initial Setup

Part 2. Shared Project

Part 3. Administration Service

Part 4. Identity Service

Part 5. SaaS Service

Part 6. DB Migration

Part 7. Yarp and Tye

Part 8. Identity server and Angular App

Part 9. Distributed event bus

Part 10. Docker and CI/CD

Part 11. Add a New service (this post)

Part 12. Central Logging

Table of contents

Intro

In this post, we will add a new service to our microservice application.

Create service script

1$serviceNameInput = $args[0]
2
3$solution = Get-ChildItem *.sln | Select-Object -First 1 | Get-ItemProperty -Name Name
4$name = (Get-Item $solution.PSPath).Basename
5$pascalCase = $serviceNameInput -replace '(?:^|_)(\p{L})', { $_.Groups[1].Value.ToUpper() }
6$service = $pascalCase + "Service"
7$folder = $serviceNameInput.ToLower()
8
9abp new "$name.$service" -t module --no-ui -o services\$folder
10Remove-Item -Recurse -Force (Get-ChildItem -Path "services\$folder" -Recurse -Include *.IdentityServer)
11Remove-Item -Recurse -Force (Get-ChildItem -Path "services\$folder" -Recurse -Include *.MongoDB.Tests)
12Remove-Item -Recurse -Force (Get-ChildItem -Path "services\$folder" -Recurse -Include *.MongoDB)
13Remove-Item -Recurse -Force (Get-ChildItem -Path "services\$folder" -Recurse -Include *.Host.Shared)
14Remove-Item -Recurse -Force (Get-ChildItem -Path "services\$folder" -Recurse -Include *.Installer)
15dotnet sln ".\$name.sln" add (Get-ChildItem -Path "services\$folder" -Recurse -Include *.csproj)

Run the script

Please make sure to run this command in the root of your project where the solution file is located.

1.\newservice.ps1 project

This script will create a new service and do some cleanup and add the project to solution.

Create shared hosting for Microservice

1dotnet new classlib -n Tasky.Microservice.Shared -o shared\Tasky.Microservice.Shared

We are creating this project as a shared project for all the new microservice.

Add the reference to AdministrationService and SaaSService

1<ItemGroup>
2  <ProjectReference Include="..\..\services\administration\src\Tasky.AdministrationService.EntityFrameworkCore\Tasky.AdministrationService.EntityFrameworkCore.csproj" />
3  <ProjectReference Include="..\..\services\saas\src\Tasky.SaaSService.EntityFrameworkCore\Tasky.SaaSService.EntityFrameworkCore.csproj" />
4  <ProjectReference Include="..\Tasky.Shared.Hosting\Tasky.Shared.Hosting.csproj" />
5</ItemGroup>

Create the TaskyMicroserviceHosting module

1[DependsOn(
2    typeof(TaskyHostingModule),
3    typeof(AdministrationServiceEntityFrameworkCoreModule),
4    typeof(SaaSServiceEntityFrameworkCoreModule)
5)]
6public class TaskyMicroserviceHosting : AbpModule
7{
8
9}

Now we have the shared project we can use for all the new microservice

Prepare the host project

Add the reference the of the Shared microservice project

1<ProjectReference Include="..\..\..\..\shared\Tasky.Shared.Microservice.Hosting\Tasky.Shared.Microservice.Hosting.csproj" />

Update the DependsOn in the host project

1[DependsOn(
2    typeof(TaskyMicroserviceHosting),
3    typeof(ProjectServiceApplicationModule),
4    typeof(ProjectServiceEntityFrameworkCoreModule),
5    typeof(ProjectServiceHttpApiModule)
6    )]

Update the host port to 7004

Update the appsettings.json

1{
2  "App": {
3    "CorsOrigins": "http://localhost:4200"
4  },
5  "ConnectionStrings": {
6    "ProjectService": "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=TaskyProjectService;Pooling=false;",
7    "SaaSService": "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=TaskySaaSService;Pooling=false;",
8    "AdministrationService": "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=TaskyAdministrationService;Pooling=false;"
9  },
10  "Redis": {
11    "Configuration": "127.0.0.1"
12  },
13  "AuthServer": {
14    "Authority": "https://localhost:7000/",
15    "RequireHttpsMetadata": "false",
16    "SwaggerClientId": "ProjectService_Swagger",
17    "SwaggerClientSecret": "1q2w3e*"
18  },
19  "RabbitMQ": {
20    "Connections": {
21      "Default": {
22        "HostName": "localhost"
23      }
24    },
25    "EventBus": {
26      "ClientName": "Tasky_ProjectService",
27      "ExchangeName": "Tasky"
28    }
29  }
30}

Update the EF core project

create a ProjectServiceDbContextFactory in the EF core project

1public class ProjectServiceDbContextFactory : IDesignTimeDbContextFactory<ProjectServiceDbContext>
2{
3    public ProjectServiceDbContext CreateDbContext(string[] args)
4    {
5        var configuration = BuildConfiguration();
6
7        var builder = new DbContextOptionsBuilder<ProjectServiceDbContext>()
8            .UseNpgsql(GetConnectionStringFromConfiguration());
9
10        return new ProjectServiceDbContext(builder.Options);
11    }
12
13    private static string GetConnectionStringFromConfiguration()
14    {
15        return BuildConfiguration()
16            .GetConnectionString(ProjectServiceDbProperties.ConnectionStringName);
17    }
18
19    private static IConfigurationRoot BuildConfiguration()
20    {
21        var builder = new ConfigurationBuilder()
22            .SetBasePath(
23                Path.Combine(
24                    Directory.GetParent(Directory.GetCurrentDirectory())?.Parent!.FullName!,
25                    $"host{Path.DirectorySeparatorChar}Tasky.ProjectService.HttpApi.Host"
26                )
27            )
28            .AddJsonFile("appsettings.json", false);
29
30        return builder.Build();
31    }
32}

Create a project API

Create the project entity

1public class Project : AggregateRoot<Guid>, IMultiTenant
2{
3    public string Name { get; set; }
4
5    public Guid? TenantId { get; set; }
6
7    public Project(string name)
8    {
9        Name = name;
10    }
11}

Add Projects to the DbContext

1public DbSet<Project> Projects { get; set; }

Update the ProjectServiceDbContextModelCreatingExtensions in the ConfigureProjectService method

1builder.Entity<Project>(b =>
2{
3    //Configure table & schema name
4    b.ToTable(ProjectServiceDbProperties.DbTablePrefix + "Projects", ProjectServiceDbProperties.DbSchema);
5
6    b.ConfigureByConvention();
7});

Update the ProjectServiceEntityFrameworkCoreModule in the AddAbpDbContext

1context.Services.AddAbpDbContext<ProjectServiceDbContext>(options =>
2{
3    options.AddDefaultRepositories(true);
4});

Prepare for the migration

Add the ef core design nuget for the migrations.

1<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.1">
2    <PrivateAssets>all</PrivateAssets>
3    <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
4</PackageReference>

Once this is created delete EntityFrameworkCore folder can be created from the host project.

Migration

To create migrations

dotnet ef migrations add Init

To update database

dotnet ef database update

Create feature definition in contracts

Add the Feature package

1<PackageReference Include="Volo.Abp.Features" Version="5.2.0" />

Create ProjectServiceFeatures for the constants

1public class ProjectServiceFeatures
2{
3    public const string GroupName = "ProjectService";
4
5    public static class Project
6    {
7        public const string Default = GroupName + ".Project";
8    }
9}

Create ProjectServiceFeaturesDefinitionProvider for creating permissions

1public class ProjectServiceFeaturesDefinitionProvider : FeatureDefinitionProvider
2{
3    public override void Define(IFeatureDefinitionContext context)
4    {
5        var myGroup = context.AddGroup(ProjectServiceFeatures.GroupName);
6        myGroup.AddFeature(
7            ProjectServiceFeatures.Project.Default, 
8            defaultValue: "false",            
9            displayName: L("Project"),
10            valueType: new ToggleStringValueType());
11    }
12
13    private static LocalizableString L(string name)
14    {
15        return LocalizableString.Create<ProjectServiceResource>(name);
16    }
17}

Create permission

Create ProjectServicePermissions file

1public const string GroupName = "ProjectService";
2
3public static class Project
4{
5    public const string Default = GroupName + ".Project";
6    public const string Create = Default + ".Create";
7}

Create ProjectServicePermissionDefinitionProvider file

1public class ProjectServicePermissionDefinitionProvider : PermissionDefinitionProvider
2{
3    public override void Define(IPermissionDefinitionContext context)
4    {
5        var projectGroup = context.AddGroup(ProjectServicePermissions.GroupName, L("Permission:ProjectService"));
6        var projectPermission = projectGroup.AddPermission(ProjectServicePermissions.Project.Default, L("Permission:ProjectService:Default"));
7        projectPermission.AddChild(ProjectServicePermissions.Project.Create);
8
9    }
10
11    private static LocalizableString L(string name)
12    {
13        return LocalizableString.Create<ProjectServiceResource>(name);
14    }
15}

Create AppService Contract

Create ProjectDto file

1public class ProjectDto : EntityDto<Guid>
2{
3    public string Name { get; set; }
4}

Create IProjectAppService file

1public interface IProjectAppService : IApplicationService
2{
3    Task<List<ProjectDto>> GetAllAsync();
4
5    Task<ProjectDto> Create(ProjectDto projectDto);
6}

Create AppService in the Application

Create ProjectAppService file

1[RequiresFeature(ProjectServiceFeatures.Project.Default)]
2[Authorize(ProjectServicePermissions.Project.Default)]
3public class ProjectAppService : ProjectServiceAppService, IProjectAppService
4{
5    private readonly IRepository<Project, Guid> repository;
6
7    public ProjectAppService(IRepository<Project, Guid> repository)
8    {
9        this.repository = repository;
10    }
11
12    [Authorize(ProjectServicePermissions.Project.Default)]    
13    public async Task<List<ProjectDto>> GetAllAsync()
14    {
15        var projects = await repository.GetListAsync();
16        return ObjectMapper.Map<List<Project>,List<ProjectDto>>(projects);
17    }
18
19    [Authorize(ProjectServicePermissions.Project.Create)]
20    public async Task<ProjectDto> Create(ProjectDto projectDto)
21    {
22        var project = await repository.InsertAsync(new Project(projectDto.Name));
23        return new ProjectDto
24        {
25            Name = project.Name
26        };
27    }
28}

Create a Controller

1[Area(ProjectServiceRemoteServiceConsts.ModuleName)]
2[RemoteService(Name = ProjectServiceRemoteServiceConsts.RemoteServiceName)]
3[Route("api/project")]
4public class ProjectController : ProjectServiceController, IProjectAppService
5{
6    private readonly IProjectAppService _projectService;
7
8    public ProjectController(IProjectAppService sampleAppService)
9    {
10        _projectService = sampleAppService;
11    }
12
13    [HttpGet]
14    public async Task<List<ProjectDto>> GetAllAsync()
15    {
16        return await _projectService.GetAllAsync();
17    }
18
19    
20    [HttpPost]    
21    public async Task<ProjectDto> Create(ProjectDto projectDto)
22    {
23        return await _projectService.Create(projectDto);
24    }
25}

Update the DbMigrator project

Add the project reference for the new service

1<ProjectReference Include="..\..\services\project\src\Tasky.ProjectService.Application.Contracts\Tasky.ProjectService.Application.Contracts.csproj" />
2<ProjectReference Include="..\..\services\project\src\Tasky.ProjectService.EntityFrameworkCore\Tasky.ProjectService.EntityFrameworkCore.csproj" />

Update the dependency

1typeof(ProjectServiceEntityFrameworkCoreModule),
2typeof(ProjectServiceApplicationContractsModule)

Update the MigrateAllDatabasesAsync function in the TaskyDbMigrationService file

1await MigrateDatabaseAsync<ProjectServiceDbContext>(cancellationToken);

Update the appsettings.json

1{
2  "ConnectionStrings": {
3    "SaaSService": "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=TaskySaaSService;Pooling=false;",
4    "IdentityService": "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=TaskyIdentityService;Pooling=false;",
5    "AdministrationService": "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=TaskyAdministrationService;Pooling=false;",
6    "ProjectService": "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=TaskyProjectService;Pooling=false;"
7  },
8  "ApiScope": [
9    "AuthServer",
10    "SaaSService",
11    "IdentityService",
12    "AdministrationService",
13    "ProjectService"
14  ],
15  "ApiResource": [
16    "AuthServer",
17    "SaaSService",
18    "IdentityService",
19    "AdministrationService",
20    "ProjectService"
21  ],
22  "Clients": [
23    {
24      "ClientId": "Tasky_Web",
25      "ClientSecret": "1q2w3e*",
26      "RootUrls": [
27        "https://localhost:5000"
28      ],
29      "Scopes": [
30        "SaaSService",
31        "IdentityService",
32        "AdministrationService",
33        "ProjectService"
34      ],
35      "GrantTypes": [
36        "hybrid"
37      ],
38      "RedirectUris": [
39        "https://localhost:5000/signin-oidc"
40      ],
41      "PostLogoutRedirectUris": [
42        "https://localhost:5000/signout-callback-oidc"
43      ],
44      "AllowedCorsOrigins": [
45        "https://localhost:5000"
46      ]
47    },
48    {
49      "ClientId": "Tasky_App",
50      "ClientSecret": "1q2w3e*",
51      "RootUrls": [
52        "http://localhost:4200"
53      ],
54      "Scopes": [
55        "AuthServer",
56        "SaaSService",
57        "IdentityService",
58        "AdministrationService",
59        "ProjectService"
60      ],
61      "GrantTypes": [
62        "authorization_code"
63      ],
64      "RedirectUris": [
65        "http://localhost:4200"
66      ],
67      "PostLogoutRedirectUris": [
68        "http://localhost:4200"
69      ],
70      "AllowedCorsOrigins": [
71        "http://localhost:4200"
72      ]
73    },
74    {
75      "ClientId": "AdministrationService_Swagger",
76      "ClientSecret": "1q2w3e*",
77      "RootUrls": [
78        "https://localhost:7001"
79      ],
80      "Scopes": [
81        "SaaSService",
82        "IdentityService",
83        "AdministrationService",
84        "ProjectService"
85      ],
86      "GrantTypes": [
87        "authorization_code"
88      ],
89      "RedirectUris": [
90        "https://localhost:7001/swagger/oauth2-redirect.html"
91      ],
92      "PostLogoutRedirectUris": [
93        "https://localhost:7001/signout-callback-oidc"
94      ],
95      "AllowedCorsOrigins": [
96        "https://localhost:7001"
97      ]
98    },
99    {
100      "ClientId": "IdentityService_Swagger",
101      "ClientSecret": "1q2w3e*",
102      "RootUrls": [
103        "https://localhost:7002"
104      ],
105      "Scopes": [
106        "SaaSService",
107        "IdentityService",
108        "AdministrationService",
109        "ProjectService"
110      ],
111      "GrantTypes": [
112        "authorization_code"
113      ],
114      "RedirectUris": [
115        "https://localhost:7002/swagger/oauth2-redirect.html"
116      ],
117      "PostLogoutRedirectUris": [
118        "https://localhost:7002"
119      ],
120      "AllowedCorsOrigins": [
121        "https://localhost:7002"
122      ]
123    },
124    {
125      "ClientId": "SaaSService_Swagger",
126      "ClientSecret": "1q2w3e*",
127      "RootUrls": [
128        "https://localhost:7003"
129      ],
130      "Scopes": [
131        "SaaSService",
132        "IdentityService",
133        "AdministrationService",
134        "ProjectService"
135      ],
136      "GrantTypes": [
137        "authorization_code"
138      ],
139      "RedirectUris": [
140        "https://localhost:7003/swagger/oauth2-redirect.html"
141      ],
142      "PostLogoutRedirectUris": [
143        "https://localhost:7003"
144      ],
145      "AllowedCorsOrigins": [
146        "https://localhost:7003"
147      ]
148    },
149    {
150      "ClientId": "ProjectService_Swagger",
151      "ClientSecret": "1q2w3e*",
152      "RootUrls": [
153        "https://localhost:7004"
154      ],
155      "Scopes": [
156        "SaaSService",
157        "IdentityService",
158        "AdministrationService",
159        "ProjectService"
160      ],
161      "GrantTypes": [
162        "authorization_code"
163      ],
164      "RedirectUris": [
165        "https://localhost:7004/swagger/oauth2-redirect.html"
166      ],
167      "PostLogoutRedirectUris": [
168        "https://localhost:7004"
169      ],
170      "AllowedCorsOrigins": [
171        "https://localhost:7004"
172      ]
173    }
174  ]
175}

Prepare the Administration service

Add reference to the ProjectService.Application.Contracts project.

1<ProjectReference Include="..\..\..\project\src\Tasky.ProjectService.Application.Contracts\Tasky.ProjectService.Application.Contracts.csproj" />

Update the dependency in the Admin Host

1typeof(ProjectServiceApplicationContractsModule)

Repo: https://github.com/antosubash/Tasky

Buy Me a Coffee at ko-fi.com