Skip to content

Register and resolve with inteface

Joshua Hegedus edited this page Nov 5, 2023 · 5 revisions

The recommended Microsoft approach is to use interfaces. You can register something to the collection with the following syntax:

collection.AddSingleton<TInterface, TImplementation>();

The advantage of this is that you can create two implementation for the same interface. We can see an example in a game where there needed to be a WinForms and a WPF project. These frameworks are not quite compatible with each other.

There is a ITileFactory which has two different implementation one for each framework:

These are separately registered for their specific project, and this way, the core backend logic can reference the interface not caring about which is the implementation behind it.

Example

public interface IExampleSerice

internal class ExampleService : IExampleSerice
{
   public ExampleService(IServiceA servicA, ISmallService smallService, IBigService bigService)
   {
      // Do the assignments
   }
}

Registering and using it:

var collection = new ServiceCollection();  
collection.AddSingleton<IExampleService, ExampleService>()
var provider = collection.BuildServiceProvider();
var exService = provider.GetRequiredService<IExampleService>();

Real life example

We also follow this style in the module of the project:

collection.AddScoped<ILogger, Logger.Logger>(_ => new Logger.Logger(Guid.NewGuid()));
collection.AddScoped<IWriter, Writer>();
collection.AddScoped<IReader, Reader>();
collection.AddScoped<IDataParser, DefaultDataParser>()

References

Clone this wiki locally