My understanding of interfaces is that they define contracts and classes implementing the interface sign the contract. In that case, we may design classes to depend on the contract and not on the concrete implementation. This has advantages like reducing coupling, enabling polymorphism, and so forth.
Now I have came across one use of interfaces which I didn't get. This is from the ASP.NET Core documentation, regarding configuration. In particular, in the page, one is talking about setting up MongoDB with ASP.NET Core.
They basically define a class and an interface like this:
namespace BooksApi.Models
{
public class BookstoreDatabaseSettings : IBookstoreDatabaseSettings
{
public string BooksCollectionName { get; set; }
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
public interface IBookstoreDatabaseSettings
{
string BooksCollectionName { get; set; }
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
}
Then they use this as follows:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<BookstoreDatabaseSettings>(
Configuration.GetSection(nameof(BookstoreDatabaseSettings)));
services.AddSingleton<IBookstoreDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value);
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
I must say I gon't get it. The objects of type BookstoreDatabaseSettings
are meant to work as DTOs for the settings. They don't provide any functionality at all. So why introduce one interface in the middle?
I don't see here one usage on which one would use some other implementation. I don't see here why one is trying to decouple this, I don't see any use of polymorphism at all, and I really didn't get the point.
So why in this situation, when dealing with settings in ASP.NET Core, one uses interfaces and not the concrete class (for example BookstoreDatabaseSettings
) directly?
Aucun commentaire:
Enregistrer un commentaire