Categories
C# Tutorials

Get a service using its name in AspCore

We all know that we can get services by injecting them directly in the constructor of the class and consume them as we want.

but imagine that you are developing an a generic component in which this component receive the name of service that will be used to get some data for this component, so how we can have an instance for that service as we don’t know its type and we only have its name?

By default, .Net allow us to get instances for registered services using the constructor or by using IServiceProvider GetService() and GetRequiredService() methods, but in order to use these methods we have to know the type of the service which it is not the case here!

Categories
C# Tutorials

Automatically register services in Asp Core

As application business logic get more and more complex we as developers need to develop more and more services and repositories in order to use them to implement the business logic model. and of course we need to register these repositories and services in our app Dependency injection container in order to inject them anywhere in our application.

The Ordinary way for registering repositories and services, is by using the program.cs class and add these services one by one, which is in fact is not a good idea, and not even practical, as this class will contain more and more repeated registering of different classes, and the class will get more noisy by time.

The idea I’m trying to clarify here, is how about if we can register all our application services/repositories with only one line like:

builder.Services.RegisterAppServices();