user989988
user989988

Reputation: 3746

Dependency Injection - directory inject one class in another class

I have a MailRepository class with the following structire:

public class MailRepository : IMailRepository
{
    public MailRepository()
    {
    }

    public async Task SendMail(string subject, string content, string recipientAddress)
    {  
    }
}

I also have a LocalizationReposiory class with the following code:

public class LocalizationRepository : ILocalizationRepository
{
    private readonly IStringLocalizer<LocalizationRepository> _localizer = null;
    public LocalizationRepository(IStringLocalizer<LocalizationRepository> localizer)
    {
        _localizer = localizer;
    }

    public string TranslateSetting(string settingName, params string[] additionalParams)
    {
        return _localizer.GetString(settingName, additionalParams);
    }
}

This is how I call SendMail method in MailRepository from a class:

var subject = _localizationRepository.TranslateSetting("Subject");
var content = _localizationRepository.TranslateSetting("Body");
await _mailRepository.SendMail(subject, content, "[email protected]");

This is how dependency injection in startup looks like:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddSingleton<IMailRepository>(services => new MailRepository());
        builder.Services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });
        builder.Services.Configure<RequestLocalizationOptions>(opts =>
        {
            var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("en-US")
                    };
            opts.DefaultRequestCulture = new RequestCulture("en-US");
            opts.SupportedCultures = supportedCultures;
            opts.SupportedUICultures = supportedCultures;
        });
        builder.Services.AddSingleton<ILocalizationRepository, LocalizationRepository>();
    }
}

Is there a way to inject the LocalizationRepository directly into MailRepository in order to avoid duplicating the following lines of code in multiple classes?

var subject = _localizationRepository.TranslateSetting("Subject");
var content = _localizationRepository.TranslateSetting("Body");
await _mailRepository.SendMail(subject, c,ontent "[email protected]");

Upvotes: 0

Views: 1278

Answers (1)

JohanP
JohanP

Reputation: 5472

Inject ILocalizationRepository into MailRepository

public MailRepository(ILocalizationRepository localizationRepo)
{
   //set private var
}

and then change how you register it in service provider

builder.Services.AddSingleton<IMailRepository, MailRepository>();

Upvotes: 2

Related Questions