I am looking at refactoring and abstracting some code for learning purposes.
I have created this class:
using System;
namespace app.Classes
{
public class Emailer : ISender
{
public Emailer(IConfiguration config, IHostingEnvironment env)
{
}
...
}
Then I have another class I would like to use that class:
namespace app.Notifications
{
public class PasswordReset : INotification
{
Emailer emailer = new Emailer();
public PasswordReset()
{
}
...
}
Since the IConfiguration and IHostingEnvironment are using DI, how do I keep from having to pass them through when I instantiate a new Emailer inside PasswordReset?
Instead of having PasswordReset
create a new instance of Emailer
, you should leverage the existing DI and turn Emailer
into a Service.
Inside the ConfigureServices()
method in Startup.cs
, add a reference to your Emailer
class:
services.AddScoped<ISender, Emailer >();
Then change PasswordReset
to reference your new ISender
service:
namespace app.Notifications
{
public class PasswordReset : INotification
{
private ISender _emailer;
public PasswordReset(ISender emailer)
{
_emailer = emailer;
}
...
}
Now you no longer need to worry about passing anything around, DI is handling it for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.