2

我对 ASP.NET MVC 非常陌生,我需要帮助使用 Ninject 在单例范围内加载某些类型。

--- 现有代码看起来像 ----

List<Type> types = loading some types into list here.

foreach (var type in types.Where(O => O.Name.StartsWith("I")))
{
    Kernel.Bind(type).To(Type.GetType(type.FullName.Replace(".I", ".")));
}

我的工作是在单例范围内绑定这些类型,我不知道该怎么做。

4

2 回答 2

3

还可以查看 Ninject 约定扩展。它使这样的事情变得容易得多。例如,你可以这样写。

kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.Where(types.Contains)
.BindDefaultInterface()
.Configure(b => b.InSingletonScope()));

根据您获取类型列表的方式,这可能会更容易编写。只需查看 wiki 上的文档和示例。

https://github.com/ninject/ninject.extensions.conventions/wiki

于 2013-04-22T11:15:15.660 回答
3

kernel.Bind().To()放好后.InSingletonScope()

于 2013-04-22T10:24:35.403 回答