2020-09-26 19:13:56 -04:00
|
|
|
|
using SharedLibraryCore.Interfaces;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
|
|
|
|
|
namespace IW4MAdmin.Application.Misc
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// implementation of IScriptPluginServiceResolver
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class ScriptPluginServiceResolver : IScriptPluginServiceResolver
|
|
|
|
|
{
|
|
|
|
|
private readonly IServiceProvider _serviceProvider;
|
|
|
|
|
|
|
|
|
|
public ScriptPluginServiceResolver(IServiceProvider serviceProvider)
|
|
|
|
|
{
|
|
|
|
|
_serviceProvider = serviceProvider;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public object ResolveService(string serviceName)
|
|
|
|
|
{
|
2020-09-28 21:32:53 -04:00
|
|
|
|
var serviceType = DetermineRootType(serviceName);
|
|
|
|
|
return _serviceProvider.GetService(serviceType);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public object ResolveService(string serviceName, string[] genericParameters)
|
|
|
|
|
{
|
|
|
|
|
var serviceType = DetermineRootType(serviceName, genericParameters.Length);
|
|
|
|
|
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());
|
|
|
|
|
string generatedName = $"{serviceName}{(genericParamCount == 0 ? "" : $"`{genericParamCount}")}".ToLower();
|
|
|
|
|
var serviceType = typeCollection.FirstOrDefault(_type => _type.Name.ToLower() == generatedName);
|
2020-09-26 19:13:56 -04:00
|
|
|
|
|
|
|
|
|
if (serviceType == null)
|
|
|
|
|
{
|
2020-09-28 21:32:53 -04:00
|
|
|
|
throw new InvalidOperationException($"No object type '{serviceName}' defined in loaded assemblies");
|
2020-09-26 19:13:56 -04:00
|
|
|
|
}
|
|
|
|
|
|
2020-09-28 21:32:53 -04:00
|
|
|
|
return serviceType;
|
2020-09-26 19:13:56 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|