Вы можете рассмотреть следующий фрагмент кода
Код: Выделить всё
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();
var str = service.PerfomSomething(scope);
Console.WriteLine($"RES : {str}");
}
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
{
services.AddTransient();
}
);
}
Код: Выделить всё
public class DummyService : IDummyService
{
private IDictionary _dictionary;
public Task InitializeAsync()
{
_dictionary = new Dictionary();
_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);
}
Есть совет?
Спасибо
Подробнее здесь: https://stackoverflow.com/questions/700 ... crosoft-di
Мобильная версия