Tany
Tany

Reputation: 1322

Autofac InstancePerRequest scope in Azure Function

I am trying to have a dependency registered to share an instance per run of Eventhub triggered Azure Function (create new instance each time Azure function runs).

I tried register like below:

builder.RegisterType<TrialClass>().As<ITrialClass>().InstancePerRequest(); 

But it fails saying

No scope with a tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested

Is there a way to handle this case ?

.

Upvotes: 1

Views: 1016

Answers (1)

Fabio Cavalcante
Fabio Cavalcante

Reputation: 12538

Two issues here:

  1. DI not truly supported in Azure Functions today, making registration and injection difficult.
  2. Event Hubs triggered functions do not execute within the context of a web request, so to built in per request lifetime supported by Autofac would not work

If you have Autofac in a semi working state today, you can try @mjwills' suggestion and define a lifetime scope for a given invocation (this will not be as trivial as using the per request functionality, but doable).

We do have work happening in the WebJobs SDK and the Functions Host/Runtime to enhance the DI story. Some of the work is related or dependent on the .NET core migration you can track here.

Upvotes: 4

Related Questions