ninject / Ninject

the ninja of .net dependency injectors
http://ninject.org/
Other
2.67k stars 531 forks source link

GetAll<T> InScope #356

Open mcopjan opened 5 years ago

mcopjan commented 5 years ago

This is more a question as I have been stuck on this for a while.

I have the following binding Bind<IClient>().To<Safari>().When(b => configuration.Target.Equals(Target.Safari)).InScope(ctx => NUnit.Framework.Internal.TestExecutionContext.CurrentContext.CurrentTest.Id);

Sometimes when creating of a new instance of Safari fails I am still stepping into test TearDown and making sure I close client instance using

kernel.Get<IClient>().Quit(); and kernel.Get<IClient>().Dispose();

if there is no instance of IClient in scope, Ninject correctly tries to activate one . I want to prevent that. So I was hoping to get my instance from the list of activated instances using kernel.GetAll<IClient>() but I need to somehow filter this list and get activated instance InScope() as there may be multiple instances in the list when tests are running in parallel. Is there a way to do so? Or any other way really? Any help would be much appreciated.

drieseng commented 5 years ago

Do you want to just dispose the IClient instance, or any service created in the scope? You probably know this but once the scope is finalized, any instances in that scope will be released as well. If you enable the disposable strategy, any instances that implement IDisposable will be disposed when the scope is finalized. However, I suppose you don't want to rely on the GC to kick in.

mcopjan commented 5 years ago

@drieseng yes I want to dispose IClient instance, the problem is I still don't know how to get IClient instance in my test scope. Let me give you a bit more details about my scenario:

So question stays the same, in TearDown method I need to get client instance in my test scope, if there is no instance it is ok I will just don't do anything. And yes I would not mind to dispose any services in the scope at this point.

drieseng commented 5 years ago

As I said, the easiest approach right now is to enable the disposable strategy, and clear the scope in the TearDown method. Let me know if you want some sample code for this.

mcopjan commented 5 years ago

@drieseng a sample code would be appreciated thanks. For now the way I resolved my problem was moving activation of client from its constructor so when I get instance of client I can check whether it was activated or not based on client property.