48

I'm trying to Bind a generic IRepository<> interface to my generic Repository<> - however it always return null?

I have tried various things like:

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

However if I pass in a non-generic interface and class then it works like a dream?

TheBoyan
  • 6,802
  • 3
  • 45
  • 61
ebb
  • 9,297
  • 18
  • 72
  • 123

2 Answers2

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

This is the correct syntax for binding an open generic.

If you are receiving null back when requesting IRepository< of whatever >, then there may be some other problem in an area of code you haven't shared.

Steven
  • 166,672
  • 24
  • 332
  • 435
quentin-starin
  • 26,121
  • 7
  • 68
  • 86
  • Perfect! - Yes you were right. My Repository consturctor depended on a Interface - I now also have binded the Interface used by my Repository and it works! - Thanks. – ebb Dec 06 '10 at 20:37
  • 5
    @qes What would be the syntax if IRepository takes more than one type argument (i.e. `IRepository`). Please see http://stackoverflow.com/q/6740992/88709 Thanks. – Daniel Liuzzi Jul 19 '11 at 00:26
3

See my answer on MVC3 Controller constructor + Ninject.

Generic Binding works correctly in Ninject. Try using a parameterless constructor in Repository. I think the problem is there.

Community
  • 1
  • 1
Remo Gloor
  • 32,665
  • 4
  • 68
  • 98