I'm following an existing code base trying to understand DI lifetimes, in the following code, we have a Factory class that is registered as a singleton which returns an instance from a dictionary if it exists or creates a new transient instance and returns it while storing it in the dictionary.
My question is whether the transient instances created and stored inside the factory will begin acting like a singleton? Is this a good coding approach?
My Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddHostedService<Consumer>()
.AddSingleton<IPipelineFactory, PipelineFactory>()
.AddTransient<IPipeline, Pipeline>();
var app = builder.Build();
app.MapGet("/", (IPipelineFactory pipelineFactory) =>
{
return $"Total pipelines: {pipelineFactory.GetPipelineCount()}";
});
app.Run();
My Factory implementation,
public class PipelineFactory : IPipelineFactory
{
private readonly Dictionary<int, IPipeline> _pipelines = new();
private readonly IServiceProvider _serviceProvider;
public PipelineFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IPipeline GetPipeline(int pipelineId)
{
if (!_pipelines.ContainsKey(pipelineId))
{
using var scope = _serviceProvider.CreateScope();
_pipelines.Add(pipelineId, scope.ServiceProvider.GetRequiredService<IPipeline>());
}
return _pipelines[pipelineId];
}
public int GetPipelineCount()
{
return _pipelines.Count;
}
}