Ninject property injection not working
Asked Answered
F

1

5

I am new in Ninject and I need some help to move on.

I have a solution that consists of web.form (presentation) and various other class libraries projects.

In web.form application inside NinjectWebCommon cs file I have the following

kernel.Bind<HttpContext>()
      .ToMethod(ctx => HttpContext.Current).InThreadScope();

kernel.Bind<HttpContextBase>()
      .ToMethod(ctx => new HttpContextWrapper(HttpContext.Current)).InTransientScope();

kernel.Bind<MPIBE.DESTINATION.CORE.SiteContext>()
      .ToMethod(ctx => new MPIBE.DESTINATION.CORE.SiteContext(
                           new HttpContextWrapper(HttpContext.Current)
       ));

I am trying to get an instance of a class (following the constructor)

public SessionUtilities(SiteContext siteContext)
{
    _siteContext = siteContext;
}

and I noticed that i can get the instance only form web.forms application and I can't get from other projects (class libraries). Does this make any sense?

I am trying to get the instance via property injection

[Inject]
public SessionUtilities _sessionUtilities { get; set; }
Fourflush answered 30/9, 2013 at 10:6 Comment(0)
M
12

I suspect the class that contains your _sessionUtilities property is being created with new instead of via Ninject.

Ninject will only inject your _sessionUtilities property if the containing instance is also created by Ninject, either because it is created with kernel.Get() or because it is itself being injected.

Madlynmadman answered 1/10, 2013 at 16:43 Comment(7)
The instance is created via property injection as shown above and not by using the "new".Fourflush
I'm talking about the instance of the containing class. The class which contains the _sessionUtilities property. How is that created?Madlynmadman
This class instantiated via new... so, this class needs to instantiated with ninject as well?Fourflush
Yes! Dependency injection is turtles all the way down.Madlynmadman
@Madlynmadman That's useful information. Is there a way to get an instance of a Kernel in a non Ninject created instance? I'm trying to inject into a colleagues class in a referenced project which has no access to the current Kernel.Sacramentalist
Yes @Ian, it's possible via a static ServiceLocator, such as the one described in this article. However, a service locator is considered a code smell, since your code is then tightly coupled to the service locator. It would be better to pass a SessionUtilitiesProvider class instead.Madlynmadman
@shamp00: I've actually asked a question about this #23990446 if you'd be up for providing an answer with a brief example of the SessionUtlitiesProvider?Sacramentalist

© 2022 - 2024 — McMap. All rights reserved.