I am having a problem with creating 2 immutable objects where both of them have a dependency on each other. Question: How do I solve this situation keeping these objects immutable?
public class One
{
private readonly Another another;
public One(Another another)
{
this.another = another;
}
}
public class Another
{
private readonly One one;
public Another(One one)
{
this.one = one;
}
}
Its not possible to do what you suggest, unless you at least allow for dependency injection on one of the classes, as follows:
You may then have to consider putting some sort of protection logic (Exceptions?) in Another.setOne() so that the One object can only be set once.
Also consider that you may have problems instantiating
Anotherusing the default constructor without initializing theonevariable, in which case you may have to remove the readonly attribute and use the aforementioned logic in setOne()OR
You could create the
Oneclass and internally have it create theAnotherclass with a reference toOne. This might increase the coupling between the two, but would do what you need, as folows: