Home > Back-end >  inject all services in startup.cs, .net core, overloaded
inject all services in startup.cs, .net core, overloaded

Time:12-30

This is more a general question.

But I have a question about injecting services in the startup.cs:

public void ConfigureServices(IServiceCollection services)
        {            

            services.AddControllers(opt =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })
                .AddFluentValidation(config =>
            {
                config.RegisterValidatorsFromAssemblyContaining<Create>();
            });
            services.AddApplicationServices(Configuration);
            services.AddIdentityServices(Configuration);           
        }

So anyway I split the services in other file:

public static class StartupExtensionClass
    {
        public static IServiceCollection AddApplicationServices(this IServiceCollection services,
            IConfiguration Configuration)
        {

            services.AddSwaggerGen(c =>
          {
              c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
          });

            services.AddDbContext<DataContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {

                    policy.AllowAnyMethod().AllowAnyHeader().WithOrigins("http://localhost:3000");


                });
            });

            services.AddMediatR(typeof(List.Handler).Assembly);
            services.AddAutoMapper(typeof(MappingProfiles).Assembly);
            services.AddScoped<IUserAccessor, UserAccessor >();
            services.AddScoped<IPhotoAccessor, PhotoAccessor>();
            services.Configure<CloudinarySettings>(Configuration.GetSection("Cloudinary"));

            return services;

        }

But for example if you have hundreds of services. IS that not overloading the application in the start phase?

Because all the services will initialized in the beginning.

Is there not a way just to initialise some services when they will directly been called.

Like lazy loading

Thank you

CodePudding user response:

I believe you are just setting up what the runtime will use when a class of the specified type is asked for....you aren't creating the classes immediately. So if your application just started up, but you never made any request to it, it isn't like 100 classes were just instantiated for no reason.

  • Related