只是想知道是否有绑定类型和解析集合的方法。我不知道Ninject是否可以开箱即用。我正在使用MVC4和Ninject3,所以我有NinjectWebCommon.cs,我在那里注册服务。我无处可以获得内核(我读到从其他地方访问内核是不好的做法,但这肯定是解决方案)。
例如,我正在上课:
public class CacheManager
{
public IEnumerable<SelectListItem> Get<T>() where T : INameValue
我希望能够发送
CacheManager.Get<City>
并获取CityRepository类。
答案 0 :(得分: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(ICity)实现或一个实现但有几个实例(比如从数据库中检索城市名称列表并为每个名称创建一个实例)。你可以通过this.Bind&gt;()。ToProvider(...)绑定来解决。
答案 1 :(得分: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();
}
我不知道这是不好的做法(因为理论上的内核只应该用于初始化阶段),但我没有找到任何其他方法来做到这一点。
如果有更好的选择,请告诉我。