Multiprocotol Terminalprogram (BAT)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
MultiTerm/Common/StartupHelpers/ServiceExtensions.cs

40 lines
1.9 KiB

using Microsoft.Extensions.DependencyInjection;
namespace Common.StartupHelpers;
public static class ServiceExtensions
{
/// <summary>
/// Service Extension to add an <see cref="AbstractFactory{T}"/> to Dependency Injection.
/// </summary>
/// <typeparam name="TInterface">Type of interface</typeparam>
/// <typeparam name="TImplementation">Type of implementation</typeparam>
/// <param name="services">existing service collection</param>
public static void AddAbstractFactory<TInterface, TImplementation>(this IServiceCollection services)
where TInterface : class
where TImplementation : class, TInterface
{
// add implementation to services collection
services.AddTransient<TInterface, TImplementation>();
// add factory function to services collection
services.AddSingleton<Func<TInterface>>(x => () => x.GetService<TInterface>()!);
// add factory implementation to services collection
services.AddSingleton<IAbstractFactory<TInterface>, AbstractFactory<TInterface>>();
}
/// <summary>
/// Adds a factory for subcontrols to be created.
/// For example a UserControl can be instanciated using this Service.
/// </summary>
/// <typeparam name="TSubControl">type of the subcontrol</typeparam>
/// <param name="services">existing service collection</param>
public static void AddSubControlFactory<TSubControl>(this IServiceCollection services) where TSubControl : class
{
// add to DI: the subcontrol itself
services.AddTransient<TSubControl>();
// add to DI: Func of constructor of that subcontrol
services.AddSingleton<Func<TSubControl>>(x => () => x.GetService<TSubControl>()!);
// add to DI: Factory for the subcontrol
services.AddSingleton<IAbstractFactory<TSubControl>, AbstractFactory<TSubControl>>();
}
}