It is not possible to explicitly extend the lifetime of an object with .InRequestScope() to extend to the end of the request.
If there are no business requirements that the work during the request and @callback should happen in one transaction, I would use two instances of DbContext . One during the request and one during the callback. Note. As far as I know, this also means that you cannot take an entity from the first context and update / save it in the second context. This means that you should only pass the identifier (and other data related to the operation) from the request to the callback. The callback should “create” a new DbContext and obtain the appropriate permissions from the context.
Conditional Linking Alternative
Alternatively, you can declare a special binding for this special case. Ninject supports so-called contextual bindings . This means that you will have two bindings, a standard binding and a contextual binding to a special case:
Bind<DbContext>().ToSelf().InRequestScope(); Bind<DbContext>().ToSelf() .WhenInjectedInto<SomeController>();
Note that the second binding does not indicate the scope — this means that SomeController is responsible for calling .Dispose() . In your case, this would mean that the callback would have to use the context. You should also get rid of the context in all cases of errors (errors in the callback code, errors that occur before the callback is triggered, ...).
Also, in fact your application is probably more of a bite, and .WhenInjectedInto<SomeController> will not be sufficient / correct, because you may want to inject the same instance into the controller plus the repository plus the request object .. which is not.
This means you need a scope, but the scope is different from .InRequestScope() . You can use .InCallScope() or a named scope - both are included in the named scope extension.
In addition, you will need to adapt the When condition. You can adapt it to cross requests and see if there is a FooController anywhere in the request chain. But this is not very indicative; instead, I would recommend using ninject IParameter to indicate that you want to use a special case. Parameter:
public class NonRequestScopedParameter : Ninject.Parameters.IParameter { public bool Equals(IParameter other) { if (other == null) { return false; } return other is NonRequestScopedParameter; } public object GetValue(IContext context, ITarget target) { throw new NotSupportedException("this parameter does not provide a value"); } public string Name { get { return typeof(NonRequestScopedParameter).Name; } }
which will be used for type bindings:
kernel.Bind<SomeController>().ToSelf() .WithParameter(new NonRequestScopedParameter()); kernel.Bind<DbContext>().ToSelf() .When(x => x.Parameters.OfType<NonRequestScopedParameter>().Any()) .InCallScope();