如何将依赖配置与 ASP.NET Core Blazor Web App 的 UI 项目分离?

问题描述 投票:0回答:1

我有一个 Blazor Web 应用程序,其 .NET 8 中的 服务器托管 模型具有

WebApplication.CreateBuilder
最小托管模型。

在该解决方案中,我使用多个库项目在整个应用程序中培育一个“干净的架构”,最值得注意的是,我精确控制了“项目相互引用”的方式。这样,从技术上来说,域模型项目意外引用持久性(数据库)项目中的类型是不可能的。 与每个默认 Blazor 应用程序一样,此 Blazor 项目当前执行两件事:

配置整个应用程序的依赖注入

托管 UI 组件
  • 第一点导致 Blazor 项目引用解决方案的其他项目。这导致任何 UI 组件现在都可以引用来自持久性项目的类型。我的目标是防止这种情况发生,以便 Blazor 组件只能了解具有 UI 接口的项目中的类型。
  • 由于配置注入的依赖项必须在托管启动过程的早期完成,所以我的想法是为托管创建一个专用项目,允许它知道任何其他项目来配置依赖项注入。这意味着我的自定义类型的
builder.Services.Add(...)

部分将不再出现在 Blazor 项目中。

我怎样才能实现这一目标?

托管项目肯定需要某种 

Program.cs

,最好使用没有

class Program

样板的顶级语句。但是在那里使用

WebApplication.CreateBuilder
有意义吗?这似乎会造成麻烦,因为托管项目必须是
<Project Sdk="Microsoft.NET.Sdk.Web">
类型,然后
ContentRootPath
/
WebRootPath
的默认行为不起作用,因为它们是在托管项目中查找的,而实际上是在布拉佐尔项目。也许还存在其他问题,我还没有发现。
    
您可以创建带有扩展方法的静态类来扩展

IServiceCollection
c# asp.net dependency-injection blazor
1个回答
0
投票

这是我的一个演示项目中的一个示例,它定义了简洁设计

基础设施
服务。

public static class ApplicationInfrastructureServices { /// <summary> /// Adds the server side Mapped Infrastructure services /// and generic handlers /// </summary> /// <param name="services"></param> public static void AddAppServerMappedInfrastructureServices(this IServiceCollection services) { services.AddDbContextFactory<InMemoryTestDbContext>(options => options.UseInMemoryDatabase($"TestDatabase-{Guid.NewGuid().ToString()}")); services.AddScoped<IDataBroker, DataBroker>(); // Add the standard handlers services.AddScoped<IListRequestHandler, ListRequestServerHandler<InMemoryTestDbContext>>(); services.AddScoped<IItemRequestHandler, ItemRequestServerHandler<InMemoryTestDbContext>>(); services.AddScoped<ICommandHandler, CommandServerHandler<InMemoryTestDbContext>>(); // Add any individual entity services services.AddMappedWeatherForecastServerInfrastructureServices(); } /// <summary> /// Adds the generic services for the API Data Pipeline infrastructure /// </summary> /// <param name="services"></param> /// <param name="baseHostEnvironmentAddress"></param> public static void AddAppClientMappedInfrastructureServices(this IServiceCollection services, string baseHostEnvironmentAddress) { services.AddHttpClient(); services.AddHttpClient(AppDictionary.Common.WeatherHttpClient, client => { client.BaseAddress = new Uri(baseHostEnvironmentAddress); }); services.AddScoped<IDataBroker, DataBroker>(); services.AddScoped<IListRequestHandler, ListRequestAPIHandler>(); services.AddScoped<IItemRequestHandler, ItemRequestAPIHandler>(); services.AddScoped<ICommandHandler, CommandAPIHandler>(); services.AddAppClientMappedWeatherForecastInfrastructureServices(); } 您可以从这里查看完整的存储库:

https://github.com/ShaunCurtis/Blazr.Demo/tree/Next

解决方案之一:

https://github.com/ShaunCurtis/Blazr.Demo/tree/Next/Source/Applications/Blazr.Weather

© www.soinside.com 2019 - 2024. All rights reserved.