Shyam Padodara
Shyam Padodara

Reputation: 73

Failed to get hosted service instance (Manually start hosted service .net core 3.1)

I had api project and test project in .net core 2.2. Now I have migrated both project in .net core 3.1

In test project I have "Initialize" method where I am adding services manually

public void Initalize(){

var services = new ServiceCollection();
services.AddDbContext<DatabaseContext>(opt =>
   opt.UseInMemoryDatabase("EdgePrototype").UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddHostedService<QueuedHostedService>();
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
services.AddSingleton<TempFileCleanupProvider>();
services.AddSingleton<IHostedService, TempFileCleanupService>();
services.AddSingleton<DbCleanupProvider>();
services.AddSingleton<IHostedService, DbCleanupService>();
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();

ServiceProvider = services.BuildServiceProvider();
ServiceScope = new Mock<IServiceScope>();
ServiceScope.Setup(x => x.ServiceProvider).Returns(ServiceProvider);
ServiceScopeFactory = new Mock<IServiceScopeFactory>();
ServiceScopeFactory
    .Setup(x => x.CreateScope())
    .Returns(ServiceScope.Object);

// Hosted Service
var service = ServiceProvider.GetService<IHostedService>() as QueuedHostedService;
service.StartAsync(CancellationToken.None);}

In .net core 2.2 above code was working perfectly, But after migration "GetService" method always return "null".

I have tried accepted answer in below question. It is working in .net core 2.2 but not working in .net core 3.1 Integration Test For Hosted Service .Net-Core`

Can any one suggest what changes I should do in above code for .net core 3.1 ?

Upvotes: 4

Views: 805

Answers (1)

Nkosi
Nkosi

Reputation: 247641

Since there appears to be multiple hosted services in the service collection, then the approach to resolve the desired hosted service for the test needs to change.

//...

// Hosted Service
IHostedService service = ServiceProvider.GetServices<IHostedService>()
    .OfType<QueuedHostedService>().First();

//Act
service.StartAsync(CancellationToken.None);}

//...

Use GetServices<T> (note the plural services) to get all registered hosted services and, using LINQ, filter out the one you want.

Upvotes: 3

Related Questions