Skip to content

Commit

Permalink
Fixed first-chance exception when resolving class with optional inter…
Browse files Browse the repository at this point in the history
…face parameter
  • Loading branch information
jnm2 committed Oct 27, 2018
1 parent 47f9c82 commit 1f642df
Showing 1 changed file with 23 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -361,12 +361,7 @@ private object ResolveFromKernelByName(CreationContext context, ComponentModel m

private object ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency)
{
IHandler handler;
try
{
handler = TryGetHandlerFromKernel(dependency, context);
}
catch (HandlerException exception)
if (!TryGetHandlerFromKernel(dependency, context, out var handler))
{
if (dependency.HasDefaultValue)
{
Expand All @@ -377,8 +372,7 @@ private object ResolveFromKernelByType(CreationContext context, ComponentModel m
"Missing dependency.{2}Component {0} has a dependency on {1}, which could not be resolved.{2}Make sure the dependency is correctly registered in the container as a service, or provided as inline argument.",
model.Name,
dependency.TargetItemType,
Environment.NewLine),
exception);
Environment.NewLine));
}

if (handler == null)
Expand Down Expand Up @@ -424,23 +418,37 @@ private object ResolveFromParameter(CreationContext context, ComponentModel mode
}
}

private IHandler TryGetHandlerFromKernel(DependencyModel dependency, CreationContext context)
private bool TryGetHandlerFromKernel(DependencyModel dependency, CreationContext context, out IHandler handler)
{
// we are doing it in two stages because it is likely to be faster to a lookup
// by key than a linear search
var handler = kernel.LoadHandlerByType(dependency.DependencyKey, dependency.TargetItemType, context.AdditionalArguments);
if (handler == null)
try
{
handler = kernel.LoadHandlerByType(dependency.DependencyKey, dependency.TargetItemType, context.AdditionalArguments);
}
catch (HandlerException)
{
throw new HandlerException(string.Format("Handler for {0} was not found.", dependency.TargetItemType), null);
handler = null;
}
if (handler == null) return false;

if (handler.IsBeingResolvedInContext(context) == false)
{
return handler;
return true;
}

// make a best effort to find another one that fit

var handlers = kernel.GetHandlers(dependency.TargetItemType);
IHandler[] handlers;
try
{
handlers = kernel.GetHandlers(dependency.TargetItemType);
}
catch (HandlerException)
{
return false;
}

foreach (var maybeCorrectHandler in handlers)
{
if (maybeCorrectHandler.IsBeingResolvedInContext(context) == false)
Expand All @@ -449,7 +457,7 @@ private IHandler TryGetHandlerFromKernel(DependencyModel dependency, CreationCon
break;
}
}
return handler;
return true;
}

private static bool IsHandlerInValidState(IHandler handler)
Expand Down

0 comments on commit 1f642df

Please sign in to comment.