我是 Ninject 的新手,我也是 stackoverflow 的新手。
我将它与 ninject.web.mvc 扩展一起使用,我能够像这样正确初始化它:
public class MvcApplication : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(AssemblyLocator.GetBinFolderAssemblies());
return kernel;
}
}
这是我的类 assemlylocator,它扫描 bin 文件夹中的所有程序集,搜索程序集中的所有 Ninject 模块。
public static class AssemblyLocator
{
private static readonly ReadOnlyCollection AllAssemblies = null;
private static readonly ReadOnlyCollection BinFolderAssemblies = null;
static AssemblyLocator()
{
AllAssemblies = new ReadOnlyCollection<Assembly>(
BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList());
IList<Assembly> binFolderAssemblies = new List<Assembly>();
string binFolder = HttpRuntime.AppDomainAppPath + "bin\\";
IList<string> dllFiles = Directory.GetFiles(binFolder, "*.dll",
SearchOption.TopDirectoryOnly).ToList();
foreach (string dllFile in dllFiles)
{
AssemblyName assemblyName = AssemblyName.GetAssemblyName(dllFile);
Assembly locatedAssembly = AllAssemblies.FirstOrDefault(a =>
AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyName));
if (locatedAssembly != null)
{
binFolderAssemblies.Add(locatedAssembly);
}
}
BinFolderAssemblies = new ReadOnlyCollection<Assembly> (binFolderAssemblies);
}
public static ReadOnlyCollection<Assembly> GetAssemblies()
{
return AllAssemblies;
}
public static ReadOnlyCollection<Assembly> GetBinFolderAssemblies()
{
return BinFolderAssemblies;
}
}
在我的控制器中一切正常:
public class ReteController : Controller
{ // // GET: /Rete/
private readonly IReteService _service;
public ReteController(IReteService _service)
{
if (_service == null)
{
throw new ArgumentNullException("IReteService");
}
this._service = _service;
}
public ActionResult Index()
{
return View(_service.getReti());
}
直到这里几乎所有东西都很容易学习,现在我的问题是,如果我需要创建一个绑定在 Ninject 的 NinjectModule 中的对象的新实例,我不知道如何从 hee 访问内核。
//this is jus a ex.
public ActionResult NewRete() {
IRete xItem = Kernel.get();
xItem.name= "hope";
return View(xItem);
}
问题是我无法从我的控制器中找到内核。我也需要在构造函数中注入它??
我希望有人能帮助我。非常感谢你们这些天给我的大力帮助。