I've got a very big list of ISample registrations in my MS.DI container, which I inject as an IEnumerable<ISample>. But at runtime I typically need a very few. MS.DI, however, always creates all items of the collection immediately, which causes a performance problem in my application.
Is there a way to allow items of an injected IEnumerable<T> to be loaded lazily, making it function as a stream, rather than a pre-populated array?
Here's my sample code that demonstrates the problem:
services.AddTransient<ISample, SampleA>();
services.AddTransient<ISample, SampleB>();
services.AddTransient<ISample, SampleC>();
public class SampleA : ISample
{
public Guid Id = FirstGuid;
public SampleA()
{
Console.WriteLine("SampleA created.");
}
}
public class SampleB : ISample
{
public Guid Id = SecondGuid;
public SampleB()
{
Console.WriteLine("SampleB created.");
}
}
public class SampleC : ISample
{
public Guid Id = ThirdGuid;
public SampleC()
{
Console.WriteLine("SampleC created.");
}
}
In other class I use service provider for creating an instance of any of these classes.
public ISample GetInstance(Guid Id)
{
return _serviceProvider.GetServices<ISample>().FirstOrDefault(d => d.Id==Id);
}
What's the best way to prevent all items to be pre-populated?