본문 바로가기

Backend/.NET

.NET - Cleaning Up Program File: Service Extension Method

반응형

In .NET, Program.cs is the entry point to the application. It contains the necessary configurations that the application needs.

The thing is that as the size of a project grows, the number of services you need would grow too and it will start to get crowded which makes it hard to read and prone to errors. So let's see how we can solve this problem.

Implementation

As the purpose is to make our code clean. Let's create a folder first for our new file.

Then add a C# class.

To use the method without instantiation, make the class 'static'

Then add a static method that returns 'IServiceCollection' in the class

public static IServiceCollection AddAPPServices() {

}

To make the method dynamic, let's add parameters. The first parameter's type is 'IServiceCollection' which is necessary to add services. The second parameter is 'IConfiguration' for additional configurations that are specific to each service. Note that when we add the 'this' keyword in front of 'IServiceCollection', we don't have to provide the value for the parameter when we call the method.

namespace API.Services
{
  public static class ServiceExtension
  {
    public static IServiceCollection AddAPPServices(this IServiceCollection services, IConfiguration config)
    {
      return services;
    }
  }
}

In the Program.cs file cut the services you want to move.

Then paste them into the method

We can directly use the 'IServiceCollection' interface so change the first part to the parameter name (here, services).

At last, add the code below in the Program.cs file in replace of the original codes to use the newly created method.

builder.Services.AddAPPServices(builder.Configuration);

It is always a good practice to keep things readable and clean. So let's clean up!

 

728x90
반응형

'Backend > .NET' 카테고리의 다른 글

Application Architecture - Repository  (0) 2023.03.30
Application Architecture - MVC  (0) 2023.03.30
How to create .NET web-API  (1) 2023.03.02
Adding Relation to DB  (0) 2023.03.02
Auto Migration and Data Seeding  (1) 2023.03.01