我正在使用 .NET 6 中的 Clean Architecture 实现一个项目。根据 Clean Architecture 原则,我们不应该引用 Web Api 中的基础设施层(表示层),我们应该只访问 Web Api 中的应用程序层。
那么如何在不违反整洁架构原则的情况下注册基础设施层的依赖项呢?我在基础设施层创建了以下扩展方法来注册依赖项:
namespace JwtWithIdentityDemo.Infrastructure.IoC
{
public static class RegisterInfrastructure
{
public static void AddInfrastructure(this IServiceCollection services,
IConfiguration configuration)
{
services.Configure<JwtSetings>(configuration.GetSection(JwtSetings.SectionName));
services.AddSingleton<IJwtTokenGenerator, JwtTokenGenerator>();
services.AddTransient<IUserManagerWrapper, UserManagerWrapper>();
// For Identity
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddScoped<UserManager<IdentityUser>>();
// For Entity Framework
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("JwtWithIdentityDemoDb"),
sqlServerOptions => sqlServerOptions.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)
.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null)
),
ServiceLifetime.Transient
);
}
}
}
如果我在 Program.cs 中调用 AddInfrastruct
方法,那么我必须添加基础设施库的引用,这违反了 Clean Architecture 的原则。
var builder = WebApplication.CreateBuilder(args);
{
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>());
builder.Services.AddApplication(builder.Configuration);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddInfrastructure(builder.Configuration)
}
最佳答案
我认为使用AddInfrastructure
在Web应用程序项目中(因此添加到基础设施的链接)并没有违反the clean architecture的主要原则(在我看来) :
Nothing in an inner circle can know anything at all about something in an outer circle. In particular, the name of something declared in an outer circle must not be mentioned by the code in the an inner circle.
Web API 和 Infrastructure
是同一级别的概念和 Program
是你的作文根。
如果你真的想变得纯粹,你可以将实际的应用程序相关的 ASP.NET Core 代码提取到一个单独的库中,并为组合根创建一个单独的项目:
- MyProject.WebService
引用所有组件,包括MyProject.Web
和MyProject.Infrastructure
并包含Program
- MyProject.Web
类库<FrameworkReference Include="Microsoft.AspNetCore.App" />
,包含 Controller 和东西 - 我的项目.基础设施
它将引入更多的仪式,但不多。
关于c# - 如何使用 .NET 6 在 Clean Architecture 中注册基础设施层依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75865116/