-
-
Notifications
You must be signed in to change notification settings - Fork 0
Register and resolve with inteface
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.
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>();
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>()
If you want to help to improve the wiki, make a Wiki Enhancement Issue
Getting started
Services
Extras