question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot resolve scoped service 'FluentEmail.Core.Interfaces.ISender' from root provider.

See original GitHub issue

I have .NET Core 2.1.2 application with IHostedService for sending email notifications. I register an email sending stuff:

    public class NotificationsFactory
    {
        public static void Register(IServiceCollection services, IAppSettings appSettings)
        {
            var client = new SmtpClient
            {
                Host = appSettings.EmailServerHost,
                Port = appSettings.EmailServerPort,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(appSettings.EmailUser, appSettings.EmailPassword)
            };

            services
                .AddFluentEmail(appSettings.EmailFrom)
                .AddSmtpSender(client);

            services.AddSingleton<IEmailNotificationProvider, EmailNotificationProvider>();
        }
    }

then inject IFluentEmailFactory in my EmailNotificationProvider

public class EmailNotificationProvider : IEmailNotificationProvider
    {
        private readonly IFluentEmailFactory _emailFactory;

        public EmailNotificationProvider(IFluentEmailFactory emailFactory)
        {
            _emailFactory = emailFactory;
        }

        public async Task<bool> SendAsync(IOrder order)
        {
            try
            {
                var body = "Test body";

                await _emailFactory.Create()
                    .To(order.Company?.Email, "User")
                    .Subject($"New Order #{order.OrderId}")
                    .Body(body, true)
                    .SetFrom("email@email.com", "Service")
                    .SendAsync();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }

but get an error “Cannot resolve scoped service ‘FluentEmail.Core.Interfaces.ISender’ from root provider.” when creating new FluentEmail from factory.

What am I doing wrong?

Issue Analytics

  • State:open
  • Created 5 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

6reactions
belidzscommented, May 23, 2020

The problem is that IFluentEmail and IFluentEmailFactory cannot be injected in the constructor because when you use the provided AddFluentEmail() helper it creates the services as transient services instead of singleton services. Only singleton services can be injected through the constructor.

You can either manually add the service as a singleton (as mentioned above) or you can use the built methods and manually create a scope using the automatically injected IServiceProvider and explicitly request a dependency injection inside the created scope:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IServiceProvider _serviceProvider;

    public Worker(ILogger<Worker> logger, IServiceProvider serviceProvider)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            var response = await scope.ServiceProvider.GetRequiredService<IFluentEmail>()
                .To("test@example.com")
                .Subject(DateTime.Now.ToLongTimeString())
                .Body("test")
                .SendAsync(stoppingToken);
        }
    }
}
6reactions
okolobaxacommented, Sep 23, 2018

Fixed by removing .AddSmtpSender(client) add adding services.AddSingleton<ISender>(x => new SmtpSender(client));

Is it a correct solution?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cannot resolve scoped service from root provider .Net Core 2
You registered the IEmailRepository as a scoped service, in the Startup class. This means that you can not inject it as a constructor ......
Read more >
DI - Cannot resolve scoped service 'FluentEmail.Core. ...
In CORE 3.1, when i register - services.AddFluentEmail("doug@doug.com") and later try to resolve by: var fact = this.serviceProvider.
Read more >
Cannot resolve scoped service 'FluentEmail.Core. ...
Cannot resolve scoped service 'FluentEmail.Core.Interfaces.ISender' from root provider. ... I have .NET Core 2.1.2 application with IHostedService ...
Read more >
Cannot resolve scoped service from root provider ASP.NET ...
Issue resolution for error -Cannot resolve scoped service from root provider ASP.NET Core. Understand the lifetime of service instances is registered, ...
Read more >
Cannot resolve scoped service from root provider .Net Core 2 ...
Inject your service as a parameter to the InvokeAsync method. Make your service a singleton one, if possible. Transform your middleware to a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found