var serviceProvider = new ServiceCollection() .AddSingleton() .BuildServiceProvider(); var myService = serviceProvider.GetService (); myService.DoSomething();
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddScopedIn this example, we are configuring an ASP.NET Core application to use MVC by registering the MVC services with the IServiceCollection. We also register a scoped instance of MyService with the service collection. We then register a singleton instance of Func(); services.AddSingleton >(sp => { return (id) => sp.GetService (); }); } public class MyController : Controller { private readonly Func _myServiceFactory; public MyController(Func myServiceFactory) { _myServiceFactory = myServiceFactory; } public IActionResult Index(int id) { var myService = _myServiceFactory(id); myService.DoSomething(); return View(); } }