Q:

How to avoid code redundance in ASP.Net Core?

I implemented SendGrid in my application, and inside the Account controller I have a method called Register. The method Register allow to the user to signup on the site, inside this method I have the following code:
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

var callbackUrl = Url.Action("ConfirmEmail", "Account", new
{
    userId = user.Id,
    token = code
}, protocol: Request.Scheme);

await _emailSender.SendEmailAsync(user.Email, _localizer["ConfirmYourEmail"], _localizer["ConfirmAccountTemplate", callbackUrl]);

as you can see I generate a confirmation code, and then I created a callBackUrl that the user can find inside the email for confirm the email address. At the end, I call SendEmailAsync which is essentially an implementation of the interface method of Microsoft.AspNetCore.Identity.UI.Services.
Now the main problem is the following: I need to use the same code inside a Repository class, so not inside a Controller, is there a place to store this type of code without create redundance?
PS: I'm sorry if this question seems stupid, but I'm actually a newbie of ASP.NET Core and I want learn to how to create a good project structure.
Thanks in advance for any help.

A:

I need to reuse the method to create the code and send the email

This is a quick mark up I didn't test if this works. You want to make something of the following, and use this in Dependency Injection (DI). You might need to add IUrlHelper and  IHttpContextAccessor
public class SomeClass : ISomeClass
{
    private HttpContext _ctx;
    private IUrlHelper _url;
    private IConfiguration _localizer;
    private IEmailSender _emailSender;
    private UserManager<ApplicationUser> _userManager;

    public SomeClass(
        IUrlHelper url,
        IHttpContextAccessor ctx,
        IConfiguration config,
        IEmailSender emailSender,
        UserManager<ApplicationUser> userManager)
    {
        _ctx = ctx.HttpContext;
        _url = url;
        _localizer = config;
        _emailSender = emailSender;
        _userManager = userManager;
    }

    public async Task SendEmailWithCode(string email)
    {
        var user = await _userManager.FindByEmailAsync(email);
        var code = await _userManager.GeneratePasswordResetTokenAsync(user);
        var callbackUrl = _url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code }, protocol:  _ctx.Request.Scheme);
        await _emailSender.SendEmailAsync(user.Email, _localizer["ConfirmYourEmail"], _localizer["ConfirmAccountTemplate"], callbackUrl);
    }
}

