Allow users to get IDependencyMap if they follow a strict format
This commit is contained in:
@@ -17,12 +17,36 @@ namespace Discord.Commands
|
|||||||
if (constructor == null)
|
if (constructor == null)
|
||||||
throw new InvalidOperationException($"Found no constructor for \"{typeInfo.FullName}\"");
|
throw new InvalidOperationException($"Found no constructor for \"{typeInfo.FullName}\"");
|
||||||
|
|
||||||
object[] parameters;
|
object[] arguments = null;
|
||||||
|
|
||||||
|
ParameterInfo[] parameters = constructor.GetParameters();
|
||||||
|
|
||||||
|
// TODO: can this logic be made better/cleaner?
|
||||||
|
if (parameters.Length == 1)
|
||||||
|
{
|
||||||
|
if (parameters[0].ParameterType == typeof(IDependencyMap))
|
||||||
|
{
|
||||||
|
if (map != null)
|
||||||
|
arguments = new object[] { map };
|
||||||
|
else
|
||||||
|
throw new InvalidOperationException($"Could not find a valid constructor for \"{typeInfo.FullName}\" (an IDependencyMap is required)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (parameters.Length == 2)
|
||||||
|
{
|
||||||
|
if (parameters[0].ParameterType == typeof(CommandService) && parameters[1].ParameterType == typeof(IDependencyMap))
|
||||||
|
if (map != null)
|
||||||
|
arguments = new object[] { service, map };
|
||||||
|
else
|
||||||
|
throw new InvalidOperationException($"Could not find a valid constructor for \"{typeInfo.FullName}\" (an IDependencyMap is required)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (arguments == null)
|
||||||
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// TODO: probably change this ternary into something sensible
|
// TODO: probably change this ternary into something sensible?
|
||||||
parameters = constructor.GetParameters()
|
arguments = parameters.Select(x => x.ParameterType == typeof(CommandService) ? service : map.Get(x.ParameterType)).ToArray();
|
||||||
.Select(x => x.ParameterType == typeof(CommandService) ? service : map.Get(x.ParameterType)).ToArray();
|
|
||||||
}
|
}
|
||||||
catch (KeyNotFoundException ex) // tried to inject an invalid dependency
|
catch (KeyNotFoundException ex) // tried to inject an invalid dependency
|
||||||
{
|
{
|
||||||
@@ -30,12 +54,13 @@ namespace Discord.Commands
|
|||||||
}
|
}
|
||||||
catch (NullReferenceException ex) // tried to find a dependency
|
catch (NullReferenceException ex) // tried to find a dependency
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException($"Could not find a valid constructor for \"{typeInfo.FullName}\" (type requires dependency injection)", ex);
|
throw new InvalidOperationException($"Could not find a valid constructor for \"{typeInfo.FullName}\" (an IDependencyMap is required)", ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return constructor.Invoke(parameters);
|
return constructor.Invoke(arguments);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in New Issue
Block a user