具有Scoped依赖关系的.Net Core 2.0 Webjob

时间:2017-12-26 07:32:47

标签: asp.net dependency-injection .net-core azure-webjobs asp.net-core-2.0

我正在构建一个使用IJobActivator设置.Net Core 2.0的webjob。如果函数是作用域的,IServiceScopeFactory.CreateScope似乎在IJobActivator中不起作用,如果它是单例,则在函数内也不起作用。

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}");
            }
        }
    }

如果函数具有作用域:激活器中将抛出异常:无法从根提供程序解析作用域服务“ValidationResultProcessorWebJob.Functions”。

如果Functions是一个单例:System.InvalidOperationException:无法从根提供程序解析作用域服务'ValidationResultProcessorWebJob.TelemetryScopeProvider'。

是否未应用_scopeFactory.CreateScope()?为什么不呢?

谢谢,

韦恩

1 个答案:

答案 0 :(得分:0)

我错误地认为IServiceScopeFactory提供了比它更多的魔力。我目前了解应该使用IServiceScopeFactory.CreateScope创建子范围。 IServiceScope包含一个ServiceProvider,然后可以用它来实例化一个新的依赖图。

我将逻辑从函数移动到新的处理器类并将其配置为Scoped。

serviceCollection.AddScoped<Functions>();
serviceCollection.AddScoped<ResponseProcesor>();
//... Other scoped dependecies e.g. EF context and repositories. 

我将IServiceScopeFactory注入WebJobs类(函数)并从中实例化一个新的对象图。

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);
        }
    }
}