【发布时间】: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