Kernel.Get<IInterface<T>> with T only known at runtime

105 views
Skip to first unread message

schaibaa

unread,
May 1, 2012, 7:29:56 PM5/1/12
to ninject
Hello,

I am wondering if something along these lines this is possible..

Lets say Foo : Bar
and Moo : Bar



void DoSomething(Bar b){

Kernel.Get<IService<b.GetType()>>();
}

Then I have bindings like:

Bind<IService<Foo>>
Bind<IService<Moo>>

Thanks!

Bartelink, Ruben

unread,
May 1, 2012, 7:59:46 PM5/1/12
to nin...@googlegroups.com
You're looking for MakeGenericType.
 
It can be used to generate the
    IService<b.GetType()>
portion by doing
    Type closedGenericType = typeofI<IService<>>).MakeGenericType(b.GetType())
 
The final piece is that alongside Get<T>(), there is a non-generic variant, Get(Type) which you use as follows:
 
var instance = Kernel.Get(closedGenericType);
 
Search "Open Generic Types" (and maybe repository) and you should find a good article or two.
 
--Ruben

schaibaa

unread,
May 2, 2012, 9:53:03 AM5/2/12
to ninject
Thank you Ruben, your response was very helpful for me. Sincerely
appreciated.
Reply all
Reply to author
Forward
0 new messages