Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Split ConfigureServices method (of Startup) into multiple files

Separation of concerns (SoC)

Dependency injunction registrtered in ConfigureServices (method of startup class) consist of different DI's like Repository, Fluent Validations etc.

How would I go about separating DI registration into separate files (as shown below)

enter image description here

like image 242
Mark Macneil Bikeio Avatar asked Jun 17 '18 15:06

Mark Macneil Bikeio


People also ask

What ConfigureServices () method does in startup CS?

The ConfigureServices method is a public method on your Startup class that takes an IServiceCollection instance as a parameter and optionally returns an IServiceProvider . The ConfigureServices method is called before Configure .

What is difference between configure and ConfigureServices?

Use ConfigureServices method to add services to the container. Use Configure method to configure the HTTP request pipeline.

Can Cs have multiple startups?

Startup class conventions: The app can define multiple Startup classes for different environments. The appropriate Startup class is selected at runtime. The class whose name suffix matches the current environment is prioritized.

Which is called first configure or ConfigureServices?

The ConfigureServices method Called by the host before the Configure method to configure the app's services.


1 Answers

Create an extension method to hold any additional configuration you want

public static class MyExtensions {
    public static IServiceCollection AddFluentValidation(this IServiceCollection services) {

        //...add services

        return services;
    }
}

And then called in the ConfigureServices in Startup

public void ConfigureServices(IServiceCollection services) {

    //...

    services.AddFluentValidation();
    services.AddRepository();

    //...

}

The use of extension methods for populating the services collection is commonly used by the framework and 3rd party extensions.

like image 126
Nkosi Avatar answered Sep 21 '22 14:09

Nkosi