【问题标题】:Azure Webjob - Per Request Lifetime?Azure Webjob - 每个请求的生命周期?
【发布时间】:2017-08-17 14:14:35
【问题描述】:

我有一个用于 azure webjob 的控制台应用程序。我需要每个 azure webjob 请求都有一个唯一的 nhibernate 会话。我正在使用 autofact 来管理 DI。

如何在 azure webjobs 中获得 Per Request Lifetime 实例化?本质上,控制台应用程序没有此功能。我需要更改项目类型吗?

我已经看到了几个关于如何做类似herehere 的答案。但它们基本上归结为将容器作为参数传递给函数。这并不是每个请求的真正实例。

【问题讨论】:

  • 你用的是什么触发器??
  • 天蓝色队列触发器
  • 队列或服务总线队列?看看这个答案stackoverflow.com/questions/35186456/… 并告诉我:-)
  • 天蓝色存储队列。
  • 哈哈是的,这是迄今为止我找到的最佳答案。覆盖 IQueueProcessorFactory。我们现在正在努力尝试。这是黑客攻击还是预期用途?是否打算被覆盖?

标签: autofac azure-webjobs


【解决方案1】:

据我所知,网络作业没有请求。它只是在应用服务 Web 应用上将程序作为后台进程运行。它无法得到请求。

在我看来,Per Request Lifetime 实例用于 Web 应用程序,如 ASP.NET Web 表单和 MVC 应用程序,而不是 webjobs。

你的请求是什么意思?

通常,我们将使用 AutofacJobActivator 在 webjobs 中使用 Instance Per Dependency。

函数触发时会自动创建新实例。

这是一个网络作业示例:

class Program
{
    // Please set the following connection strings in app.config for this WebJob to run:
    // AzureWebJobsDashboard and AzureWebJobsStorage
    static void Main()
    {
        var builder = new ContainerBuilder();
         builder.Register(c =>
        {
            var model = new DeltaResponse();
            return model;
        })
     .As<IDropboxApi>()
     .SingleInstance();
     builder.RegisterType<Functions>().InstancePerDependency();
        var Container = builder.Build();
        var config = new JobHostConfiguration()
        {
            JobActivator = new AutofacJobActivator(Container)
        };

        var host = new JobHost(config);
        // The following code ensures that the WebJob will be running continuously
        host.RunAndBlock();
    }
}

public class AutofacJobActivator : IJobActivator
{
    private readonly IContainer _container;

    public AutofacJobActivator(IContainer container)
    {
        _container = container;
    }

    public T CreateInstance<T>()
    {
        return _container.Resolve<T>();
    }
}

public interface IDropboxApi
{
    void  GetDelta();
}

public class DeltaResponse : IDropboxApi
{
    public Guid id { get; set; }

    public DeltaResponse()
    {
        id = Guid.NewGuid();
    }
    void IDropboxApi.GetDelta()
    {
        Console.WriteLine(id);
        //throw new NotImplementedException();
    }
}

函数.cs:

public class Functions
{
    // This function will get triggered/executed when a new message is written 
    // on an Azure Queue called queue.

    private readonly IDropboxApi _dropboxApi;

    public Functions(IDropboxApi dropboxApi)
    {
        _dropboxApi = dropboxApi;
    }


    public void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log)
    {
        log.WriteLine("started");

        // Define request parameters.
        _dropboxApi.GetDelta();
    }
}

当函数触发时,它会自动创建新的实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多