.Net Core 2.0 Webjob 与作用域依赖 [英] .Net Core 2.0 Webjob with Scoped Dependencies

查看:35
本文介绍了.Net Core 2.0 Webjob 与作用域依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用 IJobActivator 设置的 .Net Core 2.0 的网络作业.IServiceScopeFactory.CreateScope 如果 Functions 是作用域的,则在 IJobActivator 中似乎不起作用,如果它是单例,则在 Functions 中也不起作用.

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.

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

如果 Functions 是范围的:将在激活器中抛出异常:无法解析来自根提供程序的范围服务ValidationResultProcessorWebJob.Functions".

If Functions is scoped : The exception will be thrown in the activator: Cannot resolve scoped service 'ValidationResultProcessorWebJob.Functions' from root provider.

如果 Functions 是单例:System.InvalidOperationException:无法从根提供程序解析范围服务ValidationResultProcessorWebJob.TelemetryScopeProvider".

If Functions is a singleton: System.InvalidOperationException: Cannot resolve scoped service 'ValidationResultProcessorWebJob.TelemetryScopeProvider' from root provider.

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

Is _scopeFactory.CreateScope() not being applied? Why not?

谢谢,

韦恩

推荐答案

我错误地认为 IServiceScopeFactory 提供了比它更多的魔法.据我目前了解,应该使用 IServiceScopeFactory.CreateScope 创建子作用域.IServiceScope 包含一个 ServiceProvider,可用于实例化新的依赖关系图.

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. 

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

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

这篇关于.Net Core 2.0 Webjob 与作用域依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆