To be able to mock away objects and classes we create two constructors. One with no parameters, and one constructor that takes the dependencies.
For example:
public class MyClass
{
private readonly ISomeOtherClass someOtherClass;
public MyClass()
{
someOtherClass = new someOtherClass();
}
public MyClass(ISomeOtherClass someOtherClass)
{
this.someOtherClass = someOtherClass;
}
public void MyMethod()
{
someOtherClass.DoThis(); //Could be long-running db-call
}
}
Now, while reading http://msdn.microsoft.com/en-us/library/ms998547.aspx#scalenetchapt05%5Ftopic10 and the chapter “Prevent the Promotion of Short-Lived Objects”.
Could this design be a problem and make the objects stay in GC longer than they need to?
If so, any ideas how to fix this problem?
If you create a new instance of MyClass each time its used then someOtherClass only exists for as long as MyClass does so you aren’t unnecessarily promoting the references. If you are using MyClass as a singleton then you would probably promote both objects … but that is usually expected behavior for a singleton.