【问题标题】:Implementing Dependency Injection from a new file从新文件实现依赖注入
【发布时间】:2021-10-14 11:25:25
【问题描述】:

我一直在开发一个 ASP.NET Core 5 MVC 项目,它按预期工作,我现在唯一遇到的问题是 Startup.cs 文件的大小,我使用的是 Microsoft。 Extensions.DependencyInjection 很多,而且非常好!但正如我所提到的,这些“services.AddTransient、Scoped 或 Singleton”变得非常拥挤,有没有办法创建我自己的类来添加这些服务并从中调用它Startup.cs?。

到目前为止,我一直在尝试使用“Inject”方法创建一个静态类,该方法将返回 IServiceCollection,但它不起作用,我一直在谷歌上搜索一些示例,但看起来这不是一个“东西”。

让我分享一些示例代码:

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;
        }
    }
}

在 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();
}
            

我希望这些信息足以解决我的问题。

非常感谢!

【问题讨论】:

    标签: c# .net asp.net-mvc asp.net-core dependency-injection


    【解决方案1】:

    是的,你绝对可以做到。我一直使用它来保持我的代码整洁。您可以使用扩展方法轻松做到这一点:

    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);
        
    }
    

    然后在你的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);
        
    }
    

    【讨论】:

    • 是的......这个工作非常好!,“AddOtherServices”有一些小问题,我收到这个错误“无法转换类型的对象'Microsoft.Extensions.DependencyInjection.FluentEmailServicesBuilder ' 输入 'Microsoft.Extensions.DependencyInjection.IServiceCollection'。”,所以我决定不使用它,只使用“RegisterServices”,因为这是迄今为止最大的。非常感谢您的帮助@user15119845
    【解决方案2】:

    这是很常见的事情(因为是的 - 它确实变得拥挤!)。

    一种方法是在IServiceCollection 上编写扩展方法,将功能位组合在一起。

    例如,您可能会创建一个名为 DatabaseServices.cs 的文件,该文件会添加实体框架或 Dapper 或其他任何内容。

    // 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
        }
    } 
    

    然后在Startup.cs 你可以这样做:

    // Startup.cs
    services.AddDatabases();
    

    创建其他文件以添加日志记录、配置、服务、HTTP 客户端等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-03
      • 2023-03-14
      • 2014-01-08
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多