lukencode / FluentEmail

All in one email sender for .NET. Supports popular senders (SendGrid, MailGun, etc) and Razor templates.
https://lukelowrey.com/dotnet-email-guide-2021/
MIT License
3.03k stars 436 forks source link

Injected IFluentEmailFactory exception: IServiceProvider disposed #315

Open Xenovore opened 2 years ago

Xenovore commented 2 years ago

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?

suddenelfilio commented 2 years ago

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.

JGreenberg-Codemoto commented 1 year ago

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