简体   繁体   中英

Using Open Generics with Funq

I have the following interface:

public interface IWriter<in TId, TViewModel>

For which there are a number of different implementations such as:

public class RedisWriter<TId, TViewModel> : IWriter<TId, TViewModel> 

I'd like to be able to inject an instance of this class into the constructor of a service:

public class MyService : Service
{
    private readonly IWriter<Guid, OrderViewModel> _writer;

    public MyService(IWriter<Guid, OrderViewModel> writer)
    {
        _writer = writer;
    }
}

Notice that generic type parameters are closed over where an instance is required.

I can't see any way to do this in Funq. Is it possible? Or do other IOCs allow this kind of use?

Funq does not support building up closed implementations based on open-generic registrations. With Funq you will have to explicitly register all closed-generic implementations that the application requires. For instance:

c.Register<IWriter<Guid, OrderViewModel>>(c => new RedisWriter<Guid, OrderViewModel>());
c.Register<IWriter<int, UserViewModel>>(c => new RedisWriter<int, UserViewModel>());

do other IOCs allow this kind of use?

Yes, all the popular DI libraries support this, such as Simple Injector, Autofac, Castle Windsor, Ninject and StructureMap.

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