Page 1 of 1

ASP.NET: Wie wählt man beim Auflösen von Abhängigkeiten einen Konstruktor bedingt aus?

Posted: 08 Jan 2025, 07:43
by Guest
Ich habe 3 Klassen:

Code: Select all

public  class QuickConsoleEntryPoint     // the one I want to conditionally choose constructor
{
public QuickConsoleEntryPoint()
{
;
}

public QuickConsoleEntryPoint(QuickConsoleRunArgsManager argsParser)
{
;
}
}

public class QuickConsoleRunArgsManager
{
private readonly string[] _args;

private readonly string _hotelsArgsSwitch;
private readonly string _bookingsArgsSwitch;

public QuickConsoleRunArgsManager(QuickConsoleRunArgs runCommandArgs)
{
_args = runCommandArgs.args;

_hotelsArgsSwitch = "hotels";
_bookingsArgsSwitch = "bookings";
}

public (string HotelsFilename, string BookingsFilname) Parse()
{
var hotelRepositoryFilename = GetParameterValue(_hotelsArgsSwitch);
var bookingRepositoryFilename = GetParameterValue(_bookingsArgsSwitch);

if (hotelRepositoryFilename is null || bookingRepositoryFilename is null)
throw new ArgumentException("One or more underlying datafile names or parameters' switch not given properly.");

return (hotelRepositoryFilename, bookingRepositoryFilename);
}

private string? GetParameterValue(string key)
{
int index = Array.IndexOf(_args, "--" + key);

if (index >= 0 && _args.Length > index)
return _args[index + 1];

return null;
}
}

public class QuickConsoleRunArgs
{
public string[] args = [];
}

public  class QuickConsoleEntryPoint
{
public QuickConsoleEntryPoint()
{
;
}

public QuickConsoleEntryPoint(QuickConsoleRunArgsManager argsParser)
{
;
}
}
Ich möchte eine fließende Registrierungs-API für die Bibliothek und je nach Benutzer der Bibliothek haben.
Aufruf:

Code: Select all

public static IServiceCollection AddQuickCommandLineArguments(this IServiceCollection services, string[] consoleRunArgs)
{
services.AddSingleton(sp => {
var options = new QuickConsoleRunArgs { args = consoleRunArgs };
return options;
});

services.AddSingleton();

return services;
}
Dann registriert IoC die Klasse und fügt sie mit dem richtigen Konstruktor ein:

Code: Select all

public static IServiceCollection AddQuickConsole(this IServiceCollection services)
{
services.AddSingleton(
sp =>
{
if (sp.GetService() != null)
{
var argsManager = sp.GetService();
return new QuickConsoleEntryPoint(argsManager);
}

return new QuickConsoleEntryPoint();
});

return services;
}
Egal ob ich beide Add...()-Methoden oder nur AddQuickConsole() aufrufe, ich erhalte immer diese Ausnahme:

Dienst für Typ „QuickConsole.QuickConsoleEntryPoint“ konnte beim Versuch, „ConsoleBookingApp.UserInterface.ConsoleAppInterface“ zu aktivieren, nicht aufgelöst werden

wo ConsoleAppInterface ist einfach eine Klasse, die den vom Konstruktor eingefügten QuickConsoleEntryPoint verwendet.
Was könnte das Problem sein und wie kann man es beheben?