简体   繁体   中英

Autofac registration error: The type 'System.Collections.IEnumerable' is not an open generic class or interface type

I try to register the IPage<> interface with Autofac, but it always throws the following exception:

The type 'System.Collections.IEnumerable' is not an open generic class or interface type.

This is my code:

containerBuilder.RegisterAssemblyTypes(assembly)
                .Where(t => t.IsAssignableFrom(typeof(IList<>)))
                .AsSelf()
                .AsImplementedInterfaces();

My Interface and the implementation:

public interface IPage<T> : IList<T>
{
}

public interface Page<T> : List<T>, IPage<T>
{
}

Can you help me understand why this happens and how I can solve it?

IList<T> inherits from and IEnumerable . calling .AsImplementedInterfaces() on your types is like calling .As<IList<T>>().As<IPage>().As<IEnumerable<T>>().As<ICollection<T>>().As<IEnumerable>() I don't know exactly why but Autofac try to register IEnumerable as a closed type and it fails.

If you want to resolve IPage<T> you don't have to register your types with .AsImplementedInterfaces() you have to register it as a closed type :

builder.RegisterAssemblyTypes(assembly)
       .AsClosedTypesOf(typeof(IPage<>));

Then when you resolve IPage<Customer> , Autofac will give you a Page<Customer> instance

Try something like this:

builder.RegisterAssemblyTypes(assembly).AsClosedTypesOf(typeof(IList<>));

AsClosedTypesOf specifies that a type from a scanned assembly is registered if it implements an interface that closes the provided open generic interface type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM