neon-sprawl/server/NeonSprawl.Server/Game/Npc/NpcBehaviorCatalogServiceCo...

50 lines
2.2 KiB
C#

using Microsoft.Extensions.Options;
using NeonSprawl.Server.Game.Combat;
using NeonSprawl.Server.Game.Skills;
namespace NeonSprawl.Server.Game.Npc;
/// <summary>DI registration for the fail-fast NPC behavior catalog (NEO-88).</summary>
public static class NpcBehaviorCatalogServiceCollectionExtensions
{
/// <summary>Binds <see cref="ContentPathsOptions"/> and registers <see cref="NpcBehaviorDefinitionCatalog"/> and <see cref="INpcBehaviorDefinitionRegistry"/> as singletons.</summary>
public static IServiceCollection AddNpcBehaviorDefinitionCatalog(this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions<ContentPathsOptions>()
.Bind(configuration.GetSection(ContentPathsOptions.SectionName));
services.AddSingleton<NpcBehaviorDefinitionCatalog>(sp =>
{
var hostEnv = sp.GetRequiredService<IHostEnvironment>();
var opts = sp.GetRequiredService<IOptions<ContentPathsOptions>>().Value;
var logger = sp.GetRequiredService<ILoggerFactory>()
.CreateLogger("NeonSprawl.Server.Game.Npc.NpcBehaviorCatalog");
var npcBehaviorsDir = NpcBehaviorCatalogPathResolution.ResolveNpcBehaviorsDirectory(
opts.NpcBehaviorsDirectory,
hostEnv.ContentRootPath);
var schemaPath = NpcBehaviorCatalogPathResolution.ResolveNpcBehaviorDefSchemaPath(
npcBehaviorsDir,
opts.NpcBehaviorDefSchemaPath,
hostEnv.ContentRootPath);
var catalog = NpcBehaviorDefinitionCatalogLoader.Load(npcBehaviorsDir, schemaPath, logger);
var abilityRegistry = sp.GetRequiredService<IAbilityDefinitionRegistry>();
var crossRefErr = PrototypeE5M2NpcBehaviorCatalogRules.TryGetAttackAbilityCrossRefError(
catalog.ById,
abilityRegistry);
if (crossRefErr is not null)
{
throw new InvalidOperationException(crossRefErr);
}
return catalog;
});
services.AddSingleton<INpcBehaviorDefinitionRegistry>(sp =>
new NpcBehaviorDefinitionRegistry(sp.GetRequiredService<NpcBehaviorDefinitionCatalog>()));
return services;
}
}