using statement; why is my field not set to null?
I am trying to minimize entity framework connection context scope using "using" while at the mean time I want to be able to inject a context into my class. I searched on internet but did not find a case like mine, or I am just doing something wrong, anyway, here is code:
[TestFixture]
public class Dummy
{
private IFoo ifoo;
[Test]
public void CreateIfNotExist()
{
using (var foo = GetNewIFoo())
{
foo.Dosomething();
}
Assert.IsNull(ifoo);//test fail here
}
[Test]
public void NotCreateIfExist()
{
ifoo = new Bar();
using (var foo = GetNewIFoo())
{
foo.Dosomething();
}
Assert.IsNull(ifoo);//test fail here
}
private IFoo GetNewIFoo()
{
if (ifoo == null)
{
ifoo = new Foo();//return new Foo();
}
return ifoo;
}
}
the first test failed, with a object sequence of foo created->foo do something->foo disposed(called by using on foo) while the state variable ifoo is still type of Foo().
Second test failed, with object life sequence as same as before.
I am confused as I thought GetNewIFoo() would return a re开发者_如何学JAVAference of ifoo and using keyword would just call dispose on ifoo?
Also, is there any good way to control context scope while maintaining ability to inject IContext ?
Calling Dispose()
does not clear the references (nor does it perform garbage collection). It simply calls the Dispose()
method, which can (for example) close connections, files, etc - depending on the implementation. An object can be non-null and still disposed. Some objects allow you to see if an object is disposed; most don't.
Generally, if you are using
something, you wouldn't write that variable somewhere else (i.e. you wouldn't write it as a field somewhere).
Meaning if using
block is in next:
using (var foo = GetNewIFoo())
{
foo.Dosomething();
} // foo.Dipose() will be called automatically
which is the same as:
var foo = GetNewIFoo())
try
{
foo.Dosomething();
}
finally
{
foo.Dipose();
}
so foo
is not null
after using
, but it's disposed.
Also:
using (var foo = GetNewIFoo())
{
foo.Dosomething();
}
//^ nothing below affects ifoo!!
Assert.IsNull(ifoo); // so why reference should be null??
精彩评论