C
C#2y 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);
}
}
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);
}
}
3 Replies
phaseshift
phaseshift2y ago
What is that? It's just a resolution by name, right? You can do that with other di containers e.g. autofac
Anton
AntonOP2y ago
yeah so I need to use a library for that ok I'll check out your suggestion thanks
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server