SHARE
TWEET

Untitled

a guest Jun 26th, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. IHostBuilder builder = new HostBuilder()
  2.     .ConfigureServices((hostBuilderContext, services) => {
  3.         services.AddHostedService<MyService>();
  4.      });
  5.      
  6. public class MyService : IHostedService {
  7.     public async Task StartAsync(CancellationToken cancellationToken) { }
  8.     public async Task StopAsync(CancellationToken cancellationToken) { }
  9. }
  10.      
  11. public class MyCustomProvider : IServiceProvider {
  12.  
  13.     SomeContainer _someContainer;
  14.  
  15.     public MyCustomProvider(SomeContainer someContainer) {
  16.         _container = container;
  17.     }
  18.     public object GetService(Type serviceType) {
  19.         return _container.Get(serviceType);
  20.         // This is only called once, and serviceType is typeof(IHost)
  21.     }
  22. }
  23.      
  24. IHostBuilder builder = new HostBuilder()
  25.     .UseServiceProviderFactory(new MyContainerFactory())
  26.     .ConfigureServices((hostBuilderContext, services) => {
  27.         services.AddHostedService<MyService>();
  28.      });
  29.      
  30. class MyContainerFactory : IServiceProviderFactory<SomeContainer> {
  31.     public SomeContainer CreateBuilder(IServiceCollection services) {
  32.         return SomeContainer.SetupStuff().Create();
  33.     }
  34.     public IServiceProvider CreateServiceProvider(SomeContainer container) {
  35.         return new MyCustomProvider(container);
  36.     }
  37. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top