question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Spec test for public-no-arg generic constraint fails

See original GitHub issue

See https://github.com/aspnet/Extensions/pull/536/commits/66a64ba8fcd7d90b395f8a0af45d2a0b04be4b42#diff-e37d6761fa5732546952f42a605c42ebR14

I’m adding support for constrained open generics to the base DI package. This package fails one of the spec tests added for public no-arg constraints. I’ve verified that resolving in the base package does work:

public class NewConstrained<T> : ISingleGeneric<T>
    where T : new()
{
}

public class ClassWithNew
{
}

[Fact]
public void CanResolveMultipleServicesWhenConstrainedWithNewConstraint()
{
    var builder = new ContainerBuilder();

    builder.RegisterGeneric(typeof(NewConstrained<>)).As(typeof(ISingleGeneric<>));
    builder.RegisterGeneric(typeof(CGeneric<>)).As(typeof(ISingleGeneric<>));

    var container = builder.Build();

    Assert.Equal(2, container.Resolve<IEnumerable<ISingleGeneric<ClassWithNew>>>().Count());
    Assert.Single(container.Resolve<IEnumerable<ISingleGeneric<string>>>());
}

That test passes in Autofac. However, this new spec test fails:

[Fact]
public void PublicNoArgCtorConstrainedOpenGenericServicesCanBeResolved()
{
    // Arrange
    var collection = new TestServiceCollection();
    collection.AddTransient(typeof(IFakeOpenGenericService<>), typeof(ClassWithNoConstraints<>));
    collection.AddTransient(typeof(IFakeOpenGenericService<>), typeof(ClassWithNewConstraint<>));
    var provider = CreateServiceProvider(collection);
    // Act
    var allServices = provider.GetServices<IFakeOpenGenericService<PocoClass>>().ToList();
    var constrainedServices = provider.GetServices<IFakeOpenGenericService<ClassWithPrivateCtor>>().ToList();
    // Assert
    Assert.Equal(2, allServices.Count);
    Assert.Equal(1, constrainedServices.Count);
}

Stack trace:

[xUnit.net 00:00:01.36]     Autofac.Extensions.DependencyInjection.Test.SpecificationTests.PublicNoArgCtorConstrainedOpenGenericServicesCanBeResolved [FAIL]
Failed   Autofac.Extensions.DependencyInjection.Test.SpecificationTests.PublicNoArgCtorConstrainedOpenGenericServicesCanBeResolved
Error Message:
 Autofac.Core.DependencyResolutionException : An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = IFakeOpenGenericService`1[] (DelegateActivator), Services = [System.Collections.Generic.IEnumerable`1[[Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeOpenGenericService`1[[Microsoft.Extensions.DependencyInjection.Specification.Fakes.ClassWithPrivateCtor, Microsoft.Extensions.DependencyInjection.Specification.Tests, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]], Microsoft.Extensions.DependencyInjection.Specification.Tests, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> GenericArguments[0], 'Microsoft.Extensions.DependencyInjection.Specification.Fakes.ClassWithPrivateCtor', on 'Microsoft.Extensions.DependencyInjection.Specification.Fakes.ClassWithNewConstraint`1[T]' violates the constraint of type 'T'. (See inner exception for details.)
---- System.ArgumentException : GenericArguments[0], 'Microsoft.Extensions.DependencyInjection.Specification.Fakes.ClassWithPrivateCtor', on 'Microsoft.Extensions.DependencyInjection.Specification.Fakes.ClassWithNewConstraint`1[T]' violates the constraint of type 'T'.
-------- System.TypeLoadException : GenericArguments[0], 'Microsoft.Extensions.DependencyInjection.Specification.Fakes.ClassWithPrivateCtor', on 'Microsoft.Extensions.DependencyInjection.Specification.Fakes.ClassWithNewConstraint`1[T]' violates the constraint of type parameter 'T'.
Stack Trace:
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
   at Autofac.Core.Resolving.InstanceLookup.Execute()
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
   at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) in C:\dev\aspnet-extensions\src\DependencyInjection\DI.Abstractions\src\ServiceProviderServiceExtensions.cs:line 79
   at Microsoft.Extensions.DependencyInjection.Specification.DependencyInjectionSpecificationTests.PublicNoArgCtorConstrainedOpenGenericServicesCanBeResolved() in C:\dev\aspnet-extensions\src\DependencyInjection\DI.Specification.Tests\src\DependencyInjectionSpecificationTests.cs:line 615
----- Inner Stack Trace -----
   at System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
   at System.RuntimeType.MakeGenericType(Type[] instantiation)
   at Autofac.Features.OpenGenerics.OpenGenericServiceBinder.TryBindServiceType(Service service, IEnumerable`1 configuredOpenGenericServices, Type openGenericImplementationType, Type& constructedImplementationType, IEnumerable`1& constructedServices)
   at Autofac.Features.OpenGenerics.OpenGenericRegistrationSource.<RegistrationsFor>d__3.MoveNext()
   at Autofac.Core.Registration.ComponentRegistry.GetInitializedServiceInfo(Service service)
   at Autofac.Core.Registration.ComponentRegistry.RegistrationsFor(Service service)
   at Autofac.Features.Collections.CollectionRegistrationSource.<>c__DisplayClass0_0.<RegistrationsFor>b__0(IComponentContext c, IEnumerable`1 p)
   at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
----- Inner Stack Trace -----
   at System.RuntimeTypeHandle.Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, Int32 numGenericArgs, ObjectHandleOnStack type)
   at System.RuntimeTypeHandle.Instantiate(Type[] inst)
   at System.RuntimeType.MakeGenericType(Type[] instantiation)

My PR isn’t merged, so this is contingent on my PR getting merged. If you fix this behavior, you’ll want to open a PR with the MS DI package to remove that part about skipping this test.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:13 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
tilligcommented, Jul 31, 2019

I don’t think there’s any action to take here. We can probably just close it. I don’t believe we have any intention of implementing the behavior here.

0reactions
alsamicommented, Jul 31, 2019

Circling back from the PR, it appears this may be added to the base/default container but not added to the spec.

Should we move this issue to the autofac repository then?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unit test not recognized if i add a generic constrain to the ...
1 Answer. It isn't a generic constraint that is hurting you; a generic constraint is the " where T : SomeWhatever " part...
Read more >
Jakarta Bean Validation specification
A constraint is said to be generic if it has at least one constraint validator targeting the element annotated i.e. targeting the (returned) ......
Read more >
Hibernate Validator 8.0.1.Final - Jakarta Bean ...
The validate() method returns a set of ConstraintViolation instances, which you can iterate over in order to see which validation errors ...
Read more >
Constraints on type parameters - C# Programming Guide
Learn about constraints on type parameters. Constraints tell the compiler what capabilities a type argument must have.
Read more >
SQL error messages and exceptions
A check constraint or generated column that is defined with ' <value> ' is invalid. 42622, The name ' <name> ' is too...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found