我是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());
}
直到这里几乎所有东西都很容易学习,现在我的问题是如果我需要创建一个在NinjectModule中绑定的对象的新实例来自Ninject我不知道如何从heare访问内核。 / p>
//this is jus a ex.
public ActionResult NewRete() {
IRete xItem = Kernel.get();
xItem.name= "hope";
return View(xItem);
}
问题是我无法从控制器中找到内核。我需要在构造函数中注入它吗?
我希望有人可以帮助我。非常感谢你们这些日子给我的大帮助。
答案 0 :(得分:2)
请参阅How do I use Ninject with ActionResults while making the controller IoC-framework-agnostic?
对你来说基本相同。创建一个工厂并将其注入您的控制器。