2010-07-22 10 views
5

Sto tentando di associare due classi concrete a un'interfaccia. Quale comando dovrei usare in Ninject per farlo? Quello che sto cercando di fare è legare due classi concrete a una base di interfaccia sul nome del controller. È possibile? Suppongo che in ninject usi il. Quando vuoi dare il condizionale ma non ci sono tutorial là fuori dove ti mostrano come usare il. Quando si fa il ninject.Ninject to bind su controller diversi

risposta

8

Ecco alcuni esempi. Scopri il progetto di origine Ninject e il suo sottoprogetto Test per vari esempi di utilizzo, questa è la migliore documentazione per questo, specialmente dal momento che i documenti non sono ancora stati aggiornati per la v2.

// usage of WhenClassHas attribute 
Bind<IRepository>().To<XmlDefaultRepository>().WhenClassHas<PageAttribute>().WithConstructorArgument("contentType", ContentType.Page); 
// usage of WhenInjectedInto 
Bind<IRepository>().To<XmlDefaultRepository>().WhenInjectedInto(typeof(ServicesController)); 
Bind<IRepository>().To<XmlDefaultRepository>().WhenInjectedInto(typeof(PageController)).WithConstructorArgument("contentType", ContentType.Page); 
Bind<IRepository>().To<XmlDefaultRepository>().WhenInjectedInto(typeof(WidgetZoneController)).WithConstructorArgument("contentType", ContentType.WidgetZone); 
// you can also do this 
Bind<IRepository>().To<PageRepository>().WhenInjectedInto(typeof(PageController)).WithConstructorArgument("contentType", ContentType.Page); 
Bind<IRepository>().To<WidgetZoneRepository>().WhenInjectedInto(typeof(WidgetZoneController)).WithConstructorArgument("contentType", ContentType.WidgetZone); 
// or this if you don't need any parameters to your constructor 
Bind<IRepository>().To<PageRepository>().WhenInjectedInto(typeof(PageController)); 
Bind<IRepository>().To<WidgetZoneRepository>().WhenInjectedInto(typeof(WidgetZoneController)); 
// usage of ToMethod() 
Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current)); 

HTH

+0

provo il comando WhenInjectedInto(), ma ancora non funziona per me. Se il tuo controller ha parametri hai davvero bisogno di aggiungere WithConstructorArgument()? – Ganator

+0

No, il controller ha solo un costruttore che accetta IRepository, ma l'implementazione IRepository (nel mio caso XmlDefaultRepository) ha il costruttore che accetta il parametro contentType di tipo string, che è l'esempio di WithConstructorArgument(). – mare

+0

Nota: questi quando i metodi ...() e With ...() sono concatenabili, è possibile interrompere WhenInjectedInto(). E, sì, WhenInjectedInto() funziona per me subito, molto semplice, a patto che anche l'implementazione del modello di repository sia semplice. Puoi pubblicare il codice per l'interfaccia del tuo repository e la sua implementazione e lasciarci vedere. Inserisci anche il codice da global.asax.cs in cui hai impostato DI. – mare