Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
Implementing Dependency Injection from a new file

I`ve been working on an ASP.NET Core 5 MVC project and it is working as expected, the only issue i'm having right now is the size of the Startup.cs file, i'm using the Microsoft.Extensions.DependencyInjection a lot, and it's very good!, but as i mentioned it is getting very crowded with those "services.AddTransient, Scoped or Singleton", is there a way to create my own class to add those services and call it from the Startup.cs?.

So far i've been trying to make a static class with an "Inject" method that will return an IServiceCollection, but it is not working, i've been searching on google for some examples but it looks like this is not a "thing".

Let me share some sample code:

using FluentValidation;
using Microsoft.Extensions.DependencyInjection;
using Models;

namespace MyFirstAzureWebApp
{
    public class Injections
    {
        private static readonly IServiceCollection _services;

        public static IServiceCollection Inject()
        {
            
            _services.AddTransient<IValidator<Customer>, CustomerValidator>();
            _services.AddTransient<IValidator<Requirement, RequirementValidator>();
         _services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);
            _services
                .AddFluentEmail("noreply@myownmail.com")
                .AddRazorRenderer()
                .AddSmtpSender("smtp.myownmail.com",445);

            return _services;
        }
    }
}

And at the Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews()
                .AddFluentValidation(opt => 
                {
                    opt.DisableDataAnnotationsValidation = true;
                    opt.ValidatorOptions.LanguageManager.Culture = new CultureInfo("es");
                });

            //Dependency Injetions call
            services = Injections.Inject();
}
            

I hope this information is enougth to bring some light over my problem.

Thank you very much!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

This is quite a common thing (because yes - it does get crowded!).

One approach is to write extension methods on IServiceCollection grouping bits of functionality together.

For example, you might create a file called DatabaseServices.cs, which adds entity framework or Dapper or whatever.

// DatabaseServices.cs
public static class DatabaseServices
{
    public static IServiceCollection AddDatabases(this IServiceCollection services)
    {
         // Set up Entity Framework
         services.AddDbContext<MyContext>(/* configure EF */);
         
         // Do other stuff related to databases.

         // Return the service collection to allow chaining of calls.
         return services
    }
} 

Then in Startup.cs you can just do:

// Startup.cs
services.AddDatabases();

Create other files to add logging, configuration, services, HTTP clients, etc. etc.

over 4 years ago · Santiago Trujillo Relatório

0

yes you absolutely can do that. I use it all the time to keep my code nice and clean. You can easily do it with Extension methods:

public class Injections
{

    public static IServiceCollection RegisterServices(this IServiceCollection services) => services
        .AddTransient<IValidator<Customer>, CustomerValidator>()
        .AddTransient<IValidator<Requirement, RequirementValidator>();
        
    public static IServiceCollection AddOtherServices(this IServiceCollection services, IConfiguration configuration) =>  services
        .AddApplicationInsightsTelemetry(configuration["APPINSIGHTS_CONNECTIONSTRING"])
        .AddFluentEmail("noreply@myownmail.com")
        .AddRazorRenderer()
        .AddSmtpSender("smtp.myownmail.com",445);
    
}

Then in your Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews()
            .AddFluentValidation(opt => 
            {
                opt.DisableDataAnnotationsValidation = true;
                opt.ValidatorOptions.LanguageManager.Culture = new CultureInfo("es");
            });

    //Dependency Injetions call
    services.RegisterServices();
    services.AddOtherServices(Configuration);
    
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda