Getting InRequestScope working with Ninject and WebApi
Asked Answered
C

1

6

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://mcmap.net/q/1067065/-ninject-3-inrequestscope-not-returning-the-same-instance-for-the-same-request). 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.

Conjurer answered 9/12, 2013 at 21:35 Comment(0)
I
0

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();
Individuate answered 22/12, 2014 at 7:10 Comment(1)
Thanks for the answer. I'm probably not going to be able to verify this since a) I've forgotten the specific instance where I was trying to get this to work and b) we've long moved on to Autofac which does easily implement the features we need. If I can dig up some sample code where I was able to demonstrate the problem I'll accept this answer once I can verify it.Conjurer

© 2022 - 2024 — McMap. All rights reserved.