2

I am designing a basic logger just for educational purpose I've designed the configuration interface in such way below

public interface ILoggerConfiguration
{
    string LoggingPattern { get; set; }
    IFileLoggerConfiguration FileLogger { get; set; }
}  
  
public interface IFileLoggerConfiguration
{
    string FileName { get; set; }
    string DirectoryName { get; set; }
    string FileExtension { get; set; }
}
  
public class LoggerConfiguration : ILoggerConfiguration
{
    string LoggingPattern { get; set; }
    IFileLoggerConfiguration FileLogger { get; set; }
}
  
public class FileLoggerConfiguration : IFileLoggerConfiguration
{
    string FileName { get; set; }
    string DirectoryName { get; set; }
    string FileExtension { get; set; }
}

These all exists in the logger library(which is a class library) I have created and in the ASP.net core project I tried calling as follows.

services.AddSingleton<ILoggerConfiguration, LoggerConfiguration>(_ =>
           Configuration
               .GetSection(nameof(LoggerConfiguration))
               .Get<LoggerConfiguration>());

And I was trying to instantiate it via dependency injection then I am getting an error message as follows.

System.InvalidOperationException: 'Cannot create instance of type 'Logger.IFileLoggerConfiguration' because it is either abstract or an interface.'

I know I'm trying to instantiate the interface here is the wrong thing. I couldn't find a way to come out of this. Do somebody have some suggestion how to inject the IFileLoggerConfiguration inside ILoggerConfiguration at the time of fetching from appsettings.json?

The appsettings.json have this values as below

"LoggerConfiguration": {
"LoggingPattern": "Message|Date|LogLevel",
"FileLogger": {
  "FileName": "Test it",
  "DirectoryName": "D:\\Logger",
  "FileExtension": ".log"
}
}
Stef Heyenrath
  • 9,335
  • 12
  • 66
  • 121
mohammed mazin
  • 445
  • 3
  • 15
  • The message is clear. The configuration classes can't guess what type of object to create when all they have is an interface. Why are you using interfaces instead of classes? When a property is an interface - which class should it instantiate? There may be an infinite number of classes that implement this specific interface. – Sebastian Siemens Jan 24 '22 at 08:27
  • @SebastianSiemens Yeah you're right. I know and I can change the class structure for the same but I am looking if someone has better solution and I am new to ASP .Net core functionalities – mohammed mazin Jan 24 '22 at 09:44

1 Answers1

2

This is not possible, you indeed need to change the class structure (use only classes, no interfaces) or construct the object with the nested object yourself.

A comparable question + answer can be found here: Options pattern - Interface/Abstract property

Stef Heyenrath
  • 9,335
  • 12
  • 66
  • 121