On Mar 11, 6:47 am, Fred Chateau <
fchat...@comcast.net> wrote:
> This question is not specifically related to Ninject. It's more of a
> general coding question, but I'm posting it here in case there might be a
> better way entirely of handling the issue in Ninject, than what I am trying
> to do.
I've just finished reading a book called Dependency Injection in .NET.
You can purchase it in electronic form if you are allergic to paper
copies. Good read for foundational or even gap-filling exposure.
> I would like to know whether it is possible to access the Ninject Standard
> Kernel globally, from its instance in Global.asax.
Possible, but not recommended. What you end up with is a glorified
service locator. Which if you talk to some DI folks, like myself, this
is the DI anti-pattern; not far removed from if you simply called (new
ClassName()).
> Here is the code:
>
> public class MvcApplication : NinjectHttpApplication
> {
> protected override void OnApplicationStarted()
> {
> base.OnApplicationStarted();
>
> // MVC global registration, routing and filtering code goes
> here...
> }
>
> protected override IKernel CreateKernel()
> {
> return Container;
> }
>
> private static IKernel Container
> {
> get
> {
> IKernel kernel = new StandardKernel();
> kernel.Load(new ServiceModule(), new RepositoryModule());
> return kernel;
> }
> }
> }
I am not as familiar with the MVC pattern or with Ninject-MVC helper
facilities such as this. I've used DI more frequently in desktop
Winforms and WPF type applications.
> If I have some classes, for example, facade classes that do not interface
> with the controllers, where I would like to begin a dependency chain, my
> understanding is I should use:
>
> _className = kernel.Get<IClassName>();
>
> However, the only way I know of to do this is to create a new instance of
> the Ninject Standard kernel, but if I understand correctly, is is not a
> good idea to create a new instance of the Ninject kernel, because that is
> basically creating a second kernel.
For obvious reasons, that's correct. Hence, aptly named "kernel". Some
containers have special rules about modules as well, something about
the object life cycles. Or just generally, clarify the term, "kernel",
"module", generally "container". Read the documentation.
> So, is it possible to access the existing Kernel that was instantiated in
> Global.asax at Application Start, from anywhere in my application, or is
> there a better way entirely to do this?
When I approach the issue, I try and keep kernel access to a minimum.
If I must, I expose instance factory to just that, a single ambient
(static) factory Get<T>(params IParameter[] args). That usually works
pretty well and keeps the DI container concern as transparent as
possible to the rest of the app.
> Regards,
>
> Fred Chateau