IServiceProvider

With CatalogService defined, the team is finally able to put everything together in .NET Core. The start of all applications, that is, EXE programs, is the Main method, and .NET Core is no exception. The program is shown in the following code:

class Program
{
private static void Main(string[] args)
{
IServiceCollection services = new ServiceCollection();
ConfigureServices(services);
IServiceProvider serviceProvider = services.BuildServiceProvider();

var service = serviceProvider.GetService<ICatalogService>();
service.Run();

Console.WriteLine("CatalogService has completed.");
}

private static void ConfigureServices(IServiceCollection services)
{
// Add application services.
services.AddTransient<IUserInterface, ConsoleUserInterface>();
services.AddTransient<ICatalogService, CatalogService>();
services.AddTransient<IInventoryCommandFactory, InventoryCommandFactory>();
}
}

In the ConfigureServices method, different types are added to the IoC container including ConsoleUserInterface, CatalogService, and InventoryCommandFactory classes. The ConsoleUserInterface and InventoryCommandFactory class will be injected as required and the CatalogService class will be explicitly retrieved from the IServiceProvider interface built from the ServiceCollection object containing the added types. The program runs until the CatalogService Run method completes. 

In Chapter 5Implementing Design Patterns - .NET Core, the singleton pattern will be revisited to use the .NET Core built-in capabilities by using the IServiceCollection, AddSingleton method to control the InventoryContext instance.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.89.85