Я новичок в Ninject, и я новичок в stackoverflow.Ninject Получить экземпляр из ядра
Я использую его с 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 From Ninject Я не знаю, как получить доступ к ядру от heare.
//this is jus a ex.
public ActionResult NewRete() {
IRete xItem = Kernel.get();
xItem.name= "hope";
return View(xItem);
}
проблема в том, что я не могу найти ядро с моего контроллера. Мне нужно также ввести его в конструктор?
Я надеюсь, что кто-то может мне помочь. Большое спасибо за большую помощь, которую вы, ребята, даете мне все дни.
Hello Remo. Я встретил эту фантастическую запись от Марка Семана, http://blog.ploeh.dk/2010/08/30/DontCallTheContainerItllCallYou.aspx – 2010-12-02 14:11:48