IW4M-Admin/Application/Plugin/Script/ScriptPluginServiceResolver.cs

49 lines
1.8 KiB
C#
Raw Normal View History

2023-04-04 19:24:13 -04:00
using System;
using System.Linq;
2023-04-04 19:24:13 -04:00
using SharedLibraryCore.Interfaces;
2023-04-04 19:24:13 -04:00
namespace IW4MAdmin.Application.Plugin.Script
{
/// <summary>
/// implementation of IScriptPluginServiceResolver
/// </summary>
public class ScriptPluginServiceResolver : IScriptPluginServiceResolver
{
private readonly IServiceProvider _serviceProvider;
public ScriptPluginServiceResolver(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public object ResolveService(string serviceName)
{
var serviceType = DetermineRootType(serviceName);
return _serviceProvider.GetService(serviceType);
}
public object ResolveService(string serviceName, string[] genericParameters)
{
var serviceType = DetermineRootType(serviceName, genericParameters.Length);
2023-04-04 19:24:13 -04:00
var genericTypes = genericParameters.Select(genericTypeParam => DetermineRootType(genericTypeParam));
var resolvedServiceType = serviceType.MakeGenericType(genericTypes.ToArray());
return _serviceProvider.GetService(resolvedServiceType);
}
private Type DetermineRootType(string serviceName, int genericParamCount = 0)
{
var typeCollection = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(t => t.GetTypes());
2023-04-04 19:24:13 -04:00
var generatedName = $"{serviceName}{(genericParamCount == 0 ? "" : $"`{genericParamCount}")}".ToLower();
var serviceType = typeCollection.FirstOrDefault(type => type.Name.ToLower() == generatedName);
if (serviceType == null)
{
throw new InvalidOperationException($"No object type '{serviceName}' defined in loaded assemblies");
}
return serviceType;
}
}
}