2017-08-16 76 views
0

我有一個控制檯應用程序,我用於一個天藍色的webjob。我需要有一個獨特的nhibernate會話每個天青webjob請求。我正在使用自動執行來管理DI。Azure Webjob - 每請求一次?

我怎樣才能獲得每個請求生活在天藍色的webjobs實例?固有的控制檯應用程序沒有這個。我需要更改項目類型嗎?

我見過幾個關於如何做類似herehere的答案。但他們基本上歸結爲將一個容器作爲參數傳遞給函數。這不是每個請求的實例。

+0

你使用什麼樣的觸發器? – Thomas

+0

天青隊列觸發器 – richard

+1

隊列或服務總線隊列?看看這個答案https://stackoverflow.com/questions/35186456/azure-triggered-webjobs-scope-for-dependency-injection並讓我知道:-) – Thomas

回答

0

據我所知,webjob沒有這個請求。它只是將程序作爲App Service Web Apps的後臺進程運行。它無法獲得請求。

在我看來,Per Request Lifetime實例用於Web應用程序中,如ASP.NET Web窗體和MVC應用程序,而不是webjobs。

這是什麼意思的請求?

通常,我們將通過使用AutofacJobActivator來使用webjobs中的Instance Per Dependency。

當功能被觸發時,它會自動創建新的實例。

這裏是一個webjob例如:

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

Functions.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(); 
    } 
} 

當功能觸發,它會自動創建新的實例。