Skip to content

Singleton

Derek Williamson edited this page Sep 12, 2019 · 2 revisions

Instead of injecting with Siege or passing instances around, DnDTracker implements the Singleton concept.

Singleton Registration for DnDTracker.Web

At the start of Program.Main(), all service instances are registered in sequential order. If you need to create a new service instance, insert it at the end of the chain or with load order in mind. Do not duplicate or load a service before its reference services are loaded.

var singleton = Singleton.Initialize()
    .Add<EnvironmentConfig>(new EnvironmentConfig())
    // ...
    .Add<YourService>(new YourService()) // <---
    ;

Singleton Registration for DnDTracker.Tests

Singleton registration for unit tests is slightly different:

  1. For a unit test Setup(), use .Override<T>(object o)
  2. For any TestFixture (such as UnitTestFixture), use .Add<T>(object o) as shown in the section above.

When setting up a unit test, you most likely will want to insert Mock<> services in place of real ones. This can be done by manipulating the unit test MockSingleton:

var persisterMock = new Mock<DynamoDbPersister>();
MockSingleton
    .Override<DynamoDbPersister>(persisterMock.Object); // <---

Note: MockSingleton is only meant for use in Setup(), BeforeFirst(), and AfterLast(). Beyond that, you may use the static Singleton, as shown in the section below.

Service Instance Retrieval

At any point after registration, you may access your instance through T Singleton.Get<T>():

var tableMap = Singleton.Get<TableMap>(); // <---
var logsTable = tableMap[typeof(LogObject)]; // Retrives the associated table for LogObject.