Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to register all classes of a particular interface using .net core default service container

In unity I can register all types of an interface from an assembly using this way.

    public static void RegisterTypes(IUnityContainer container)
    {

        container.RegisterTypes(
            AllClasses.FromLoadedAssemblies().
                Where(
                    type =>
                        typeof (IRunAtInit).IsAssignableFrom(type),
            WithMappings.FromAllInterfaces,
            WithName.TypeName);

              }

Is it possible to implement it .net core like this way using its own default service container ?

like image 919
Anik Saha Avatar asked Jul 05 '16 21:07

Anik Saha


People also ask

What are the methods used to register the DI service in ConfigureServices method?

We can add the service to the service container in the ConfigureServices method of the startup class. There are three different life options available: Transient, Scoped, and Singleton.

What is difference between AddTransient and AddScoped and AddSingleton?

Singleton is a single instance for the lifetime of the application domain. Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET. Transient is a single instance per code request.

Which of the following class in .NET Core is for adding all the dependencies to the DI system?

DependencyInjection. So, in the startup class, inside the ConfigureServices method, we need to add our dependency into the service collection which will dynamically inject whenever and wherever we want in the project. Also, we can mention which kind of instance we want to inject - the lifetime of our instance.

How do I register services in NET Core 6?

For registering the interface and classes, you need to go in the Program class (As Startup class is no more with . NET 6) and use these methods i.e "AddScoped" || "AddTransient" || "AddSingleton" as it defines the lifetime of the services. STEP 5 - Go to Program class and register it.


1 Answers

Try use Scrutor extension: https://github.com/khellang/Scrutor

services.Scan(scan => scan
    .FromAssemblyOf<IRunAtInit>()
    .AddClasses(classes => classes.AssignableTo<IRunAtInit>())
    .AsImplementedInterfaces()
    .WithTransientLifetime());
like image 143
George Paoli Avatar answered Nov 14 '22 22:11

George Paoli