简体   繁体   中英

Registration of open generic types - type parameter mismatch

I'm trying to register all implementations of my generic repository as follows:

container.Register(typeof(IRepository<>), new[] { typeof(Repository<>).Assembly });

However, the container can't verify my configuration:

Additional information: The configuration is invalid. Creating the instance for type IErrorLogService failed. The constructor of type ErrorLogService contains the parameter with name 'errorLogRepository' and type IRepository<ErrorLog> that is not registered. Please ensure IRepository<ErrorLog> is registered, or change the constructor of ErrorLogService. Note that there exists a registration for a different type Persistence.Interfaces.Repository.Generic.IRepository<T> while the requested type is Persistence.Interfaces.Repository.Generic.IRepository<Persistence.DataModel.ErrorLog>.

Based on various SO threads , the snippet above should be the way to go. What did I miss?

My repository class:

public class Repository<T> : IRepository<T> where T : Entity { }

IRepository and Repository exists in the same assembly.

An explicit registration of each type works:

container.Register<IRepository<ErrorLog>, Repository<ErrorLog>>();

The Register(Type openGenericServiceType, IEnumerable<Assembly> assemblies) overload you are using states in its documentation:

Registers all concrete, non-generic , public and internal types in the given set of assemblies that implement the given openGenericServiceType with container's default lifestyle (which is transient by default).

Note the word "non-generic" here. This register overload is meant to batch-register all non-generic implementations of an open-generic service type. Since you have one open-generic implementation, this Register method will not find it.

Instead, you should use the Register(Type serviceType, Type implementationType) overload, that states:

Registers that a new instance of will be returned every time a serviceType is requested. If serviceType and implementationType represent the same type, the type is registered by itself. Open and closed generic types are supported.

TLDR;

Change your registration to the following:

container.Register(typeof(IRepository<>), typeof(Repository<>));

You can find more information about this in Simple Injector's documentation .

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