How do you define your own scoping mechanism?

1,717 views
Skip to first unread message

aema...@gmail.com

unread,
Mar 24, 2009, 9:05:31 PM3/24/09
to ninject
If I wanted to make a new scope type, let's say something that
encapsulates a "all requests that happen within a certain user
control", how would i go about doing that?

Nate Kohari

unread,
Mar 24, 2009, 9:55:58 PM3/24/09
to nin...@googlegroups.com
In Ninject2, you can do this by:

Bind<IService>().To<ServiceImpl>().InScope(ctx => ...);

The object returned by the callback passed to InScope() becomes the "owning" object of instances activated within the scope. This has two meanings:

1. If the callback returns the same object for more than one activation, Ninject will re-use the instance from the first activation.

2. When the object returned from the callback is garbage collected, Ninject will deactivate ("tear down", call Dispose(), etc.) any instances associated with that object.

For example, the callback used for InRequestScope() is:

ctx => HttpContext.Current

Since HttpContext.Current is set to a new instance of HttpContext on each web request, only a single instance of the service will be activated for each request, and when the request ends and the HttpContext is (eventually) collected, the instances will be deactivated.

The object returned by the callback can also implement INotifyWhenDisposed, an interface from Ninject, if you want to deterministically deactivate the "owned" instances. If the scoping object implements this interface, when it is Dispose()'d, any instances it owns will be deactivated immediately.


-Nate
Reply all
Reply to author
Forward
0 new messages