6
votes

I've got an MVC4/WebApi project that I'm trying to wire up with Ninject 3. I would like to share a particular object across a number of entities within request scope, however I understand that I need to provide some sort of implementation of InRequestScope (https://stackoverflow.com/a/10592203/173225). I've looked at the source on GitHub and it appears to simply return HttpContext.Current. I've tried that:

var messages = new List<string>();
kernel.Bind<IList<string>>()
    .ToMethod(x => messages)
    .WhenMemberHas<ServiceResultMessagesAttribute>()
    .InScope(x => HttpContext.Current);

with no luck. I've also tried to use the latest "unstable" Nuget package for Ninject.Web.WebApi (#9018) as recommended in https://groups.google.com/d/msg/ninject/rC2vhj8yvBU/NAIkNA-QrAAJ, but I get the same error (method get_InRequestScope does not have an implementation).

As for the source on GitHub, at the time of writing the last update to the relevant files was 11 months to more than a year ago, so I don't know if that is current with the unstable Nuget package or not (especially given the state of documentation for Ninject).

Can anyone provide a proper working example of how to inject the same instance of an object across more than one component within request scope?

Thanks.

1

1 Answers

0
votes

You will need Ninject.Web.Common reference from nuget or elsewhere and use the InRequestScope method.

var messages = new List<string>();
    kernel.Bind<IList<string>>()
        .ToMethod(x => messages)
        .WhenMemberHas<ServiceResultMessagesAttribute>()
        .InRequestScope();