2013-08-28 27 views
0

只是想知道是否有方法綁定類型並解析集合。我不知道Ninject是否可以開箱即用。我使用Ninject3的MVC4,所以我有註冊服務的NinjectWebCommon.cs。我無法獲得內核(我讀過從別處訪問內核是不好的做法,但那肯定是解決方案)。Ninject:如何解析對象類型的集合

例如,我在這個類:

public class CacheManager 
{ 
    public IEnumerable<SelectListItem> Get<T>() where T : INameValue 

我希望能夠發送

CacheManager.Get<City> 

,並獲得CityRepository類。

+0

我認爲這可能是一個工廠vs Ioc? –

+0

當你綁定。要()和綁定()。爲了()注入的IEnumerable ,ICollection的,IList的會導致你越來越TBAR和TFoo的一個實例。 如果您不想使用Ctor或Property注入,請使用IResolutionRoot接口:return resolutionRoot.GetAll ()。As (); – BatteryBackupUnit

回答

0

我落得這樣做:

在NinjectWebCommon.cs:

 kernel.Bind(typeof(CacheManager)) 
      .ToSelf() 
      .InSingletonScope(); 

     kernel.Bind<IDataListRepository<Locale>>() 
      .To<LocaleRepository>(); 

在CacheManager.cs:

public class CacheManager: IDisposable 
{ 
    private IKernel kernel; 

    public CacheManager(IKernel kernel) 
    { 
     this.kernel = kernel; 
    } 

    public IEnumerable<T> GetAsEnumerable<T>() 
    { 
     var rep = kernel.Get<IDataListRepository<T>>(); 
     return rep.GetAll(); 
    } 

我不知道這是不好的做法(自內核在理論上應該只用於初始化階段),但我沒有找到任何其他方式來做到這一點。

如果有更好的選擇,請讓我知道。

+0

我知道我說過這個: \t 還有一件事,我在ASPNET MVC4,所以我不應該直接訪問內核 - Kat Lim Ruiz 8月30日在4:03,但沒有找到任何其他方式 –

0

這是你想要做的嗎? :

using System.Collections.Generic; 
using System.Linq; 
using Ninject; 
using Ninject.Modules; 
using Ninject.Syntax; 

public class Temp 
{ 
    public interface ICity { } 

    public class SelectListItem 
    { 
    } 

    public class FooCity : SelectListItem, ICity { } 

    public class BarCity : SelectListItem, ICity {} 

    public class CityModule : NinjectModule 
    { 
     public override void Load() 
     { 
      this.Bind<ICity>().To<FooCity>(); 
      this.Bind<ICity>().To<BarCity>(); 
     } 
    } 

    public class CacheManager 
    { 
     private readonly IResolutionRoot resolutionRoot; 

     public CacheManager(IResolutionRoot resolutionRoot) 
     { 
      this.resolutionRoot = resolutionRoot; 
     } 

     public IEnumerable<SelectListItem> Get<T>() 
     { 
      return this.resolutionRoot.GetAll<T>().OfType<SelectListItem>(); 
     } 
    } 
} 

我不清楚,你是否有T(孵化城)或一個實現,但有些情況下的多種實現(如從數據庫中檢索城市名稱的名單,並且創造每名一個實例)。後來你可以通過this.Bind>()。ToProvider(...)綁定來解決。

+0

我認爲不完全是我需要的。讓我更好地解釋一下:我想要有幾個實體,比如城市,國家。每個都有自己的存儲庫類:IRepository 。所以我希望能夠做到像Ninject.Resolve 這樣的事情,它應該給我的IRepository 的impl。你懂我的意思嗎?我想實際上我的問題應該是:如何在ninject中創建工廠? –

+0

還有一件事,我在ASPNET MVC4中,所以我不應該直接訪問內核 –

+0

你可能想看看:https://github.com/ninject/ninject.extensions.factory,它簡化了工廠。如果命名參數ctor注入不足,您將不得不自己實現工廠。工廠對象需要將IResolutionRoot注入其ctor。 「創建」工廠方法可以建立所有必需的參數。使用resolutionRoot.Get (參數...)它可以讓ninject instanciate City對象。 – BatteryBackupUnit