lukencode / FluentEmail

All in one email sender for .NET. Supports popular senders (SendGrid, MailGun, etc) and Razor templates.

Home Page:https://lukelowrey.com/dotnet-email-guide-2021/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Injected IFluentEmailFactory exception: IServiceProvider disposed

Xenovore opened this issue · 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?

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.

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