Skip to content

Commit

Permalink
[ServiceEntry] Add hashable class that contains a service type and se…
Browse files Browse the repository at this point in the history
…rvice key, to store in a dictionary and access by both type and key.
  • Loading branch information
Aleksbgbg committed Jun 19, 2019
1 parent a088827 commit 2ccd581
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
61 changes: 61 additions & 0 deletions Wingman.Tests/Container/ServiceEntryTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
namespace Wingman.Tests.Container
{
using Wingman.Container;

using Xunit;

public class ServiceEntryTests
{
[Fact]
public void TestIdenticalEntriesIdenticalHashCode()
{
ServiceEntry serviceEntry0 = new ServiceEntry(typeof(IService), "SomeKey");
ServiceEntry serviceEntry1 = new ServiceEntry(typeof(IService), "SomeKey");

int hashCode0 = serviceEntry0.GetHashCode();
int hashCode1 = serviceEntry1.GetHashCode();

Assert.Equal(hashCode0, hashCode1);
}

[Fact]
public void TestNullServiceMatches()
{
ServiceEntry serviceEntry0 = new ServiceEntry(typeof(IService), null);
ServiceEntry serviceEntry1 = new ServiceEntry(typeof(IService), null);

int hashCode0 = serviceEntry0.GetHashCode();
int hashCode1 = serviceEntry1.GetHashCode();

Assert.Equal(hashCode0, hashCode1);
}

[Fact]
public void TestNullKeyMatches()
{
ServiceEntry serviceEntry0 = new ServiceEntry(null, "SomeKey");
ServiceEntry serviceEntry1 = new ServiceEntry(null, "SomeKey");

int hashCode0 = serviceEntry0.GetHashCode();
int hashCode1 = serviceEntry1.GetHashCode();

Assert.Equal(hashCode0, hashCode1);
}

[Fact]
public void TestDifferentEntriesDifferentHashCode()
{
ServiceEntry serviceEntry0 = new ServiceEntry(typeof(IService), "SomeKey");
ServiceEntry serviceEntry1 = new ServiceEntry(typeof(IService1), "SomeKey");

int hashCode0 = serviceEntry0.GetHashCode();
int hashCode1 = serviceEntry1.GetHashCode();

Assert.NotEqual(hashCode0, hashCode1);
}

private interface IService { }

private interface IService1 { }
}
}
33 changes: 33 additions & 0 deletions Wingman/Container/ServiceEntry.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
namespace Wingman.Container
{
using System;

internal class ServiceEntry
{
private readonly Type _serviceType;

private readonly string _key;

internal ServiceEntry(Type serviceType, string key)
{
_serviceType = serviceType;
_key = key;
}

public override int GetHashCode()
{
unchecked
{
const int prime1 = 17;
const int prime2 = 23;

int hash = prime1;

hash = (hash * prime2) + (_serviceType?.GetHashCode() ?? 0);
hash = (hash * prime2) + (_key?.GetHashCode() ?? 0);

return hash;
}
}
}
}

0 comments on commit 2ccd581

Please sign in to comment.