I am new to Ninject and I am new to stackoverflow too.
I am using it with the ninject.web.mvc extension, I was able to initialize it correctly like this:
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;
}
}
And here is my class assemlylocator that scans all the assemblies in the bin folder, searching for all the Ninject modules in the assembly.
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;
}
}
Everything works fine in my controller:
public c开发者_StackOverflowlass 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());
}
Until here almost everything was easy to learn, now my problem is that if I need to create a new instance of an object that was bind in the NinjectModule From Ninject I don't know how to acces the kernel from heare.
//this is jus a ex.
public ActionResult NewRete() {
IRete xItem = Kernel.get();
xItem.name= "hope";
return View(xItem);
}
the problem is that i am not able to find the kernel from my controller. I need to inject it too in the constructor??
I hope somebody can help me. Thank a lot for the big help that you guys give me all the days.
See How do I use Ninject with ActionResults while making the controller IoC-framework-agnostic?
It's basically the same for you. Create a factory aand inject it to your controller.
精彩评论