Ninject: How to bind an open generic with more than one type argument?
Asked Answered
W

1

24

I'm using Ninject 2.2, and I'm trying to setup a binding for an open generic that takes two type arguments. According to this answer by qes, the correct syntax to bind IRepository<T> to Repository<T> is this:

Bind(typeof(IRepository<>)).To(typeof(Repository<>));

The above syntax works perfectly if IRepository takes just one type argument, but breaks if it takes more (gives a Using the generic type 'Repository<T,U>' requires 2 type arguments compile time error.)

How can I bind IRepository<T,U> to Repository<T,U>?

Thanks.

Walz answered 19/7, 2011 at 0:21 Comment(0)
K
44
Bind(typeof(IRepository<,>)).To(typeof(Repository<,>));

Try that....

Kiwi answered 19/7, 2011 at 0:35 Comment(5)
Awesome! I would have never figured that out myself. Thanks a lot!Walz
My hero! It's so simple once you work out what to ask Google!Mauer
You rule! Never seen that kind of syntax before. Was just about to spoil my code with unnecessary generic types when I fortunately hit this postUnprofitable
You can also go from single type to double type, i.e. Bind(typeof(IRepo<>)).To(typeof(Repo<,>)); etc.Pierro
Actually, when I try to bind from single type param to double type params, i get some "The number of generic arguments provided doesn't equal the arity of the generic type definition." exceptionGrowl

© 2022 - 2024 — McMap. All rights reserved.