Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve the error message when parameter type is not registered #175

Merged
merged 2 commits into from
Nov 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 49 additions & 14 deletions src/CommandLineUtils/Conventions/ConstructorInjectionConvention.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,34 +59,69 @@ private void ApplyImpl<TModel>(ConventionContext context)

if (constructors.Length == 0)
{
throw new InvalidOperationException("Could not find any public constructors on " + typeof(TModel).FullName);
throw new InvalidOperationException(Strings.NoAnyPublicConstuctorFound(typeof(TModel)));
}

// find the constructor with the most parameters first
foreach (var ctorCandidate in constructors.OrderByDescending(c => c.GetParameters().Count()))
var (matchedCtor, matchedArgs) = (constructors.Length == 1)
// shortcut for single constructor
? FindMatchedConstructor(constructors, context.Application,
throwIfNoParameterTypeRegistered: true)
// find the constructor with the most parameters first
: FindMatchedConstructor(constructors, context.Application,
throwIfNoParameterTypeRegistered: false);

var parameterLessCtor = Array.Find(constructors, c => c.GetParameters().Length == 0);

if (matchedCtor == null && parameterLessCtor != null)
{
return;
}

if (matchedCtor == null && parameterLessCtor == null)
{
throw new InvalidOperationException(Strings.NoMatchedConstructorFound(typeof(TModel)));
}

if (matchedCtor != null)
{
(context.Application as CommandLineApplication<TModel>).ModelFactory =
() => (TModel)matchedCtor.Invoke(matchedArgs);
}
}

private (ConstructorInfo matchedCtor, object[] matchedArgs) FindMatchedConstructor(
ConstructorInfo[] constructors,
IServiceProvider services,
bool throwIfNoParameterTypeRegistered = false)
{
foreach (var ctorCandidate in constructors.OrderByDescending(c => c.GetParameters().Length))
{
var parameters = ctorCandidate.GetParameters().ToArray();
var args = new object[parameters.Length];
var matched = false;
for (var i = 0; i < parameters.Length; i++)
{
var paramType = parameters[i].ParameterType;
var service = ((IServiceProvider)context.Application).GetService(paramType);
var service = services.GetService(paramType);
if (service == null)
{
break;
if (!throwIfNoParameterTypeRegistered)
{
continue;
}
throw new InvalidOperationException(Strings.NoParameterTypeRegistered(ctorCandidate.DeclaringType, paramType));
}
args[i] = service;
matched = i == parameters.Length - 1;
}

if (matched)
{
(context.Application as CommandLineApplication<TModel>).ModelFactory =
() => (TModel)ctorCandidate.Invoke(args);
return;
if (i == parameters.Length - 1)
{
var matchedArgsLength = args.Count(x => x != null);
if (parameters.Length == matchedArgsLength)
{
return (ctorCandidate, args);
}
}
}
}
return (null, null);
}
}
}
9 changes: 9 additions & 0 deletions src/CommandLineUtils/Properties/Strings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,14 @@ public static string RemainingArgsPropsIsUnassignable(TypeInfo typeInfo)

public static string NoPropertyOrMethodFound(string memberName, Type type)
=> $"Could not find a property or method named {memberName} on type {type.FullName}";

public static string NoParameterTypeRegistered(Type modelType, Type paramType)
=> $"The constructor of type '{modelType}' contains the parameter of type '{paramType}' is not registered, Ensure the type '{paramType}' are registered in additional services with CommandLineApplication.Conventions.UseConstructorInjection(IServiceProvider additionalServices)";

public static string NoAnyPublicConstuctorFound(Type modelType)
=> $"Could not find any public constructors of type '{modelType}'";

public static string NoMatchedConstructorFound(Type modelType)
=> $"Could not found any matched constructors of type '{modelType}'";
}
}
64 changes: 64 additions & 0 deletions test/CommandLineUtils.Tests/ConstructorInjectionConventionTests.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
Expand Down Expand Up @@ -116,5 +118,67 @@ public void ItInjectsTheParentModel()
Assert.NotNull(subcmd.Model.Parent);
Assert.Same(app.Model, subcmd.Model.Parent);
}

private class TestAppWithoutPublicConstructor
{
private TestAppWithoutPublicConstructor()
{
}
}

[Fact]
public void ThrowsWhenNoAnyPublicConstructorFound()
{
var app = new CommandLineApplication<TestAppWithoutPublicConstructor>();
var ex = Assert.Throws<TargetInvocationException>(() => app.Conventions.UseConstructorInjection());
Assert.IsType<InvalidOperationException>(ex.InnerException);
Assert.Equal(Strings.NoAnyPublicConstuctorFound(typeof(TestAppWithoutPublicConstructor)), ex.InnerException.Message);
}

private class TestAppWithoutMatchedConstructor
{
public IConsole Console { get; }

public TestAppWithoutMatchedConstructor(TestConsole console)
{
Console = console;
}
}

[Fact]
public void ThrowsWhenNoMatchedConstructorFound()
{
var app = new CommandLineApplication<TestAppWithoutMatchedConstructor>();
var ex = Assert.Throws<TargetInvocationException>(() => app.Conventions.UseConstructorInjection());
Assert.IsType<InvalidOperationException>(ex.InnerException);
Assert.Equal(Strings.NoParameterTypeRegistered(typeof(TestAppWithoutMatchedConstructor), typeof(TestConsole)), ex.InnerException.Message);
}

private class TestAppWithAlternativeConstructor
{
public IConsole Console { get; }
public CommandLineApplication App { get; }

public TestAppWithAlternativeConstructor(TestConsole console, CommandLineApplication app)
{
Console = console;
App = app;
}

public TestAppWithAlternativeConstructor(IConsole console)
{
Console = console;
}
}

[Fact]
public void ItInjectsAlternativeConstructor()
{
var app = new CommandLineApplication<TestAppWithAlternativeConstructor>();
app.Conventions.UseConstructorInjection();
app.Parse();
Assert.NotNull(app.Model.Console);
Assert.IsType<PhysicalConsole>(app.Model.Console);
}
}
}