Michiel Rutting
Michiel Rutting

Reputation: 51

Using Ninject, how would I use the object currently in scope to determine if it's still in scope?

I have a scenario where an object should be reused by multiple concurrent web requests as long as a method on it returns true. The object in question is thread-safe.

So I need the object that is currently in scope to determine if it's still in scope. What would be the best way to accomplish this with Ninject?

While probably not needed to answer this question, the goal is to to reuse a Lucene IndexSearcher / IndexReader while the underlying index has not been changed. The Reader has a method IsCurrent that returns false if the index was changed.

Upvotes: 4

Views: 384

Answers (2)

Daniel Marbach
Daniel Marbach

Reputation: 2314

Hy, You can define your own scope object. As long as the scope object is alive and not changed ninject will return the same instance of the binded type. The custom scope would need to check whether IsCurrent returns false. You can have a look on how to implement custom scope in https://github.com/ninject/ninject.extensions.namedscope/tree/master/src/Ninject.Extensions.NamedScope. Be aware that you have to take care not to create objects which will never be released for GC when you develop your own scope!

Upvotes: 1

Felice Pollano
Felice Pollano

Reputation: 33272

In order to me the best to achieve what you want is to use a provider:

Bind<ILuceneIndex>().ToProvider(new LuceneIndexProvider());

and apply your logic of re-creation inside the provider.

Upvotes: 0

Related Questions