I've used other DI framework in the past, now I have to use the microsoft one (.NET Core 3.0) and I need to call a InitializeAsync method when the service is used (It's a singleton so I have only one instance in the whole app). I don't want to perform such operation in the Constructor sincec it has to make a call to a web api , and I also don't want to put a variable inside the method that the service implements and check if it's just initialized.
You can consider the following snippet of code
class Program
{
static void Main(string[] args)
{
using IHost host = CreateHostBuilder(args).Build();
ExemplifyScoping(host.Services, 1);
ExemplifyScoping(host.Services, 88);
host.RunAsync();
}
private static void ExemplifyScoping(IServiceProvider hostServices, int scope)
{
var service = hostServices.GetService<IDummyService>();
var str = service.PerfomSomething(scope);
Console.WriteLine($"RES : {str}");
}
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
{
services.AddTransient<IDummyService, DummyService>();
}
);
}
and the simplified service class
public class DummyService : IDummyService
{
private IDictionary<int, string> _dictionary;
public Task InitializeAsync()
{
_dictionary = new Dictionary<int, string>();
_dictionary.Add(1,"1");
_dictionary.Add(2,"2");
_dictionary.Add(3,"3");
_dictionary.Add(4,"4");
return Task.CompletedTask;
}
public string PerfomSomething(int id)
{
if (_dictionary.ContainsKey(id))
return _dictionary[id];
return string.Empty;
}
}
public interface IDummyService
{
Task InitializeAsync();
string PerfomSomething(int id);
}
I've seen that the DI framework has a PostConfigure
method but I don't know if it's what I need to use.
Any advice? Thanks