C#C
C#3y ago
Anton

❔ Is there some generic type for factories in asp net core?

Making such a factory kinda requires a bunch of code, and I haven't even made the standard fluent configuration helpers. Are there classes that do this generically in asp net core?
public interface ISomethingFactory
{
    ISomething Create(string schemeName);
}

public class SomethingFactory : ISomethingFactory
{
    public class Configuration
    {
        public Configuration(IReadOnlyDictionary<string, Type> providers)
        {
            Providers = providers;
        }

        public IReadOnlyDictionary<string, System.Type> Providers { get; }
    }

    private readonly Configuration _configuration;
    private readonly ServiceProvider _serviceProvider;

    public SomethingFactory(Configuration configuration, ServiceProvider serviceProvider)
    {
        _configuration = configuration;
        _serviceProvider = serviceProvider;
    }

    public ISomething Create(string schemeName)
    {
        if (!_configuration.Providers.TryGetValue(schemeName, out var providerType))
            throw new ArgumentException($"No provider found for scheme {schemeName}");

        return (ISomething) _serviceProvider.GetService(providerType);
    }
}
Was this page helpful?