Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store Ninject IKernel in a web application?

I am new to IOC in general and I'm struggling a little to understand whether what I am trying to do makes any sense. I have a web forms application in which I want to create one module to define some bindings for me. The bindings will be used to inject repositories into my business manager classes, allowing me to unit test the business managers. Also I would like to use the container to inject the Entity Framework context into my repositories that way they all share the same context per http request. So here is what I am wondering:

  1. I understand that I need to have the same kernel instance manage my object creation and their lifetime. For example if I want a one-per-httprequest type scenario I need the instance of the kernel to be available for that period of time. What if I need a singleton? Then it has to be application scoped somehow. So where exactly do I store the IKernel instance? It seems that I might want to make it a static in my Global.asax, is that the right approach and is thread safety a concern?

  2. Since I am using Bind<> to define my bindings, how do I go about making that definition in the Web/UI layer when I shouldn't be referencing my data access layer from the UI? My references look like .Web --> .Business --> DataAccess. It seems like I want to tell the kernel "hey manage my data access instances, but don't have a reference to them at compile time." A binding such as this:


    //Any object requesting an instance of AdventureWorksEntities will get an instance per request
    Bind<AdventureWorksEntities>().ToSelf().InRequestScope();

I feel like I might be approaching this incorrectly, thank you.

like image 707
e36M3 Avatar asked Aug 06 '10 13:08

e36M3


2 Answers

Re part 1- have a look at the Ninject.Web extension - it keeps a Kernel at Application level. You can then manage other resources that have shorter lifetimes within that too.

Also, have a look around here for questions and examples on EF and L2S DataContext management wrt Ninject and DI in general (it's come up[ in the last few weeks)

UPDATE: This answer to another question from the same OP is far more concrete (There's a KernelContainer class with a .Inject( object) and a .Kernel)

like image 165
Ruben Bartelink Avatar answered Nov 15 '22 11:11

Ruben Bartelink


It really depends on the complexity of your web app.

It sounds like you have a business and a data access layer; I would personally have an 'infrastructure' layer where I would store my DI repository and helper classes.

like image 1
John Weldon Avatar answered Nov 15 '22 09:11

John Weldon