Skip to content

Commit

Permalink
Adding test and returning a null if the open generic service fails to…
Browse files Browse the repository at this point in the history
… close because of a generic constraint. See aspnet#471 for discussion.
  • Loading branch information
jbogard committed Apr 9, 2018
1 parent 68b89aa commit f6cf49d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

namespace Microsoft.Extensions.DependencyInjection.Specification.Fakes
{
public class ConstrainedFakeOpenGenericService<TVal> : IFakeOpenGenericService<TVal>
where TVal : PocoClass
{
public ConstrainedFakeOpenGenericService(TVal value)
{
Value = value;
}

public TVal Value { get; }
}
}
11 changes: 10 additions & 1 deletion src/DI/ServiceLookup/CallSiteFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,16 @@ private IServiceCallSite TryCreateOpenGeneric(ServiceDescriptor descriptor, Type
{
Debug.Assert(descriptor.ImplementationType != null, "descriptor.ImplementationType != null");

var closedType = descriptor.ImplementationType.MakeGenericType(serviceType.GenericTypeArguments);
Type closedType;
try
{
closedType = descriptor.ImplementationType.MakeGenericType(serviceType.GenericTypeArguments);
}
catch
{
// This is the only way to reliably test generic constraints. See https://stackoverflow.com/questions/4864496/checking-if-an-object-meets-a-generic-parameter-constraint/4864565#4864565
return null;
}
var constructorCallSite = CreateConstructorCallSite(serviceType, closedType, callSiteChain);

return ApplyLifetime(constructorCallSite, Tuple.Create(descriptor, serviceType), descriptor.Lifetime);
Expand Down

0 comments on commit f6cf49d

Please sign in to comment.