I need advice, I hope someone can help me. I have the following class structure (simplified):
public class Bar: IDisposable {...}
public abstract class FooBase: IDisposable
{
Bar bar;
bool disposed;
internal FooBase(Bar bar)
{
this.bar=bar;
}
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
this.bar.Dispose();
}
this.disposed = true;
}
}
}
public FooA: Foo {...}
public FooB: Foo {...}
public static class FooProvider
{
public static FooA GetFooA()
{
Bar bar = new Bar();
...
return new FooA(bar);
}
public static FooB GetFooB()
{
Bar bar = new Bar();
...
return new FooB(bar);
}
...
}
When I run Code Analysis, I get Warnings CA2000 in all CreateFooX () methods of the FooProvider class. This warning displays the following message:
"Reliability: in the" FooProvider.GetFooX () "method, call System.IDisposable.Dispose on the" bar "of the object before all references to it go out of scope."
, . , "" , "CreateFooX()", , "FooX", , ", .
- , Dispose, , ?
- factory :
public static class FooProvider
{
public static FooA GetFooA()
{
Bar bar = null;
try
{
bar = new Bar();
...
return new FooA(bar);
}
catch
{
if (bar != null) bar.Dispose();
throw;
}
}
...
}
. , , , .
.