In S#arp Architecture's Entity class, how can GetHashCode get away with caching the hash code
S#arp Architecture's Entity base class currently implementats GetHashCode like this:
public override int GetHashCode()
{
if (cachedHashcode.HasValue)
return cachedHashcode.Value;
if (IsTransient())
{
cachedHashcode = base.GetHashCode();
开发者_运维百科 }
else
{
unchecked
{
int hashCode = GetType().GetHashCode();
cachedHashcode = (hashCode * HASH_MULTIPLIER) ^ Id.GetHashCode();
}
}
return cachedHashcode.Value;
}
I use bits of S#arp Architecture in my application (but not the whole system).
This particular implementation of GetHashCode seems to be causing me problems in some of my unit tests. The reason is that the hashcode is cached, so that if GetHashCode is called on an entity, after the entity is then changed the original hashcode keeps getting returned.
Now maybe this is the behaviour the S#arp devs desired, but too me it seems weird.
For example:
[Test]
public void Test()
{
var foo = new Foo();
// Console.WriteLine(foo.GetHashCode());
Session.Save(foo);
Session.Flush();
Session.Clear();
var reloadedFoo = Session.Load<Foo>(foo.Id);
Assert.That(reloadedFoo.GetHashCode() == foo.GetHashCode());
}
This test passes, but after I uncomment the first call to GetHashCode(), it fails.
Can someone explain why this isn't a problem?
My best guess is that it isn't a problem because sharp architecture uses a session per request model, so the call to Session.Load(foo.Id) would return the same instance of Foo (if you remove the session.Flush and session.Clear the test should pass), so the case you are testing for wasn't taken into consideration for a SharpArch application.
精彩评论