FluentEmail icon indicating copy to clipboard operation
FluentEmail copied to clipboard

Injected IFluentEmailFactory exception: IServiceProvider disposed

Open Xenovore opened this issue 3 years ago • 2 comments

When sending multiple emails, the first time it calls Create() it works great, but then subsequent calls fail, saying the IServiceProvider has been disposed.

	IFluentEmail fluentEmail = _fluentEmailFactory.Create();
	var email = fluentEmail
		.SetFrom( fromEmailAddress.EmailAddress, fromEmailAddress.Name ) 
		.To( toEmailAddresses )
		.CC( ccEmailAddresses )
		.BCC( bccEmailAddresses )
		.Subject( emailSubject )
		.UsingTemplateFromFile( templateFile, templateModel );

In my "startup.cs", I have this:

	services
		.AddFluentEmail( defaultEmail )
		.AddLiquidRenderer( options =>
		{
			options.FileProvider = new PhysicalFileProvider( liquidRendererRootPath );
		} )
		.AddSendGridSender( sendGridApiKey, sandBoxMode: false );

I see in the FluentEmailServiceCollectionExtensions.AddFluentEmail() definition:

	 services.TryAddTransient<IFluentEmailFactory, FluentEmailFactory>();

So, if it's added as transient, it make some sense that the IServiceProvider gets disposed. So, shouldn't IFluentEmailFactory be added as a singleton instead if we need to use it multiple times?

Or am I misunderstanding how to use the injected IFluentEmailFactory instance?

Xenovore avatar Mar 24 '22 22:03 Xenovore

are you by any chance using this in a Azure Function? We are moving from an in container hosted web api where it was working just fine, to an Azure Function where we experience the same issue.

suddenelfilio avatar Jun 28 '22 08:06 suddenelfilio

I experienced the same issue. I was using IFluentEmailFactory with the .Create() method, but subsequent attempts to send an email were resulting in the IServiceProvider already being disposed.

In my case, I had implemented my own IEmailService service, which was responsible for sending the emails using the IFluentEmailFactory.

Finally, I realized that I was registering my own IEmailService as a scoped dependency using: services.AddScoped<IEmailService, EmailService>();

The issue was fixed by switching the registration of my own email service to: services.AddSingleton<IEmailService, EmailService>();

JGreenberg-Codemoto avatar Dec 22 '22 23:12 JGreenberg-Codemoto