问题
I am building a webjob with .Net Core 2.0 set up using an IJobActivator. IServiceScopeFactory.CreateScope does not seem to work in the IJobActivator if Functions is scoped, nor within Functions if it's a singleton.
I.e.
public static void Main(string[] args)
{
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddScoped<Functions>(); //Or serviceCollection.AddSingleton<Functions>();
serviceCollection.AddScoped<TelemetryScopeProvider>();
//... Other scoped dependecies e.g. EF context and repositories.
var serviceProvider = serviceCollection.BuildServiceProvider(true);
var jobHostConfiguration = new JobHostConfiguration();
jobHostConfiguration.Queues.MaxPollingInterval = TimeSpan.FromSeconds(10);
jobHostConfiguration.Queues.BatchSize = 1;
jobHostConfiguration.JobActivator = new ProcessorActivator(serviceProvider);
jobHostConfiguration.UseServiceBus();
jobHostConfiguration.NameResolver = new QueueNameResolver()
{
ResultQueueName = ...
};
var config = new JobHostConfiguration();
var host = new JobHost(jobHostConfiguration);
host.RunAndBlock();
}
public class ProcessorActivator : IJobActivator
{
private readonly IServiceProvider _service;
private IServiceScopeFactory _scopeFactory;
public ProcessorActivator(IServiceProvider service, IServiceScopeFactory scopeFactory)
{
_service = service;
_scopeFactory = scopeFactory;
}
public T CreateInstance<T>()
{
using (var scope = _scopeFactory.CreateScope())
{
var service = _service.GetService(typeof(T));
return (T)service;
}
}
public class Functions
{
private IServiceScopeFactory _scopeFactory;
private IServiceProvider _serviceProvider;
public Functions(IServiceProvider serviceProvider, IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
_serviceProvider = serviceProvider;
}
public async Task ProcessValidationResult([ServiceBusTrigger("%Response%")
] string r)
{
var start = DateTime.UtcNow;
using (var scope = _scopeFactory.CreateScope())
{
try
{
//Deserialize the result.
var result = JsonConvert.DeserializeObject...;
var scopeProvider = _serviceProvider.GetService<TelemetryScopeProvider>(); //FAIL HERE
//Some other Logic which we dont get to
}
catch (Exception e)
{
Console.Out.WriteLine($"Error processing: {e.Message}");
}
}
}
If Functions is scoped : The exception will be thrown in the activator: Cannot resolve scoped service 'ValidationResultProcessorWebJob.Functions' from root provider.
If Functions is a singleton: System.InvalidOperationException: Cannot resolve scoped service 'ValidationResultProcessorWebJob.TelemetryScopeProvider' from root provider.
Is _scopeFactory.CreateScope() not being applied? Why not?
Thanks,
Wayne
回答1:
I mistakenly thought that IServiceScopeFactory was providing more magic than it does. As I currently understand a child scope should be created with IServiceScopeFactory.CreateScope. IServiceScope contains a ServiceProvider which can then be used to instantiate a new graph of dependencies.
I moved the logic from the function to a new processor class and configured it as Scoped.
serviceCollection.AddScoped<Functions>();
serviceCollection.AddScoped<ResponseProcesor>();
//... Other scoped dependecies e.g. EF context and repositories.
I inject IServiceScopeFactory to the WebJobs class (Functions) and instantiate a new object graph from it.
public class Functions
{
private IServiceScopeFactory _scopeFactory;
public Functions(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public async Task ProcessValidationResult([ServiceBusTrigger("%Response%")] string r)
{
using (var scope = _scopeFactory.CreateScope())
{
var processor = scope.ServiceProvider.GetService<ResponseProcesor>();
await processor.Process(r);
}
}
}
来源:https://stackoverflow.com/questions/47975348/net-core-2-0-webjob-with-scoped-dependencies