[英]How do I keep from having to pass around IConfiguration and IHostingEnvironment
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? 由于IConfiguration和IHostingEnvironment正在使用DI,因此在PasswordReset中实例化新的Emailer时如何避免将它们传递出去?
Instead of having PasswordReset
create a new instance of Emailer
, you should leverage the existing DI and turn Emailer
into a Service. 不应让PasswordReset
创建Emailer
的新实例,而应利用现有的DI并将Emailer
变成服务。
Inside the ConfigureServices()
method in Startup.cs
, add a reference to your Emailer
class: 在Startup.cs
的ConfigureServices()
方法内,添加对Emailer
类的引用:
services.AddScoped<ISender, Emailer >();
Then change PasswordReset
to reference your new ISender
service: 然后更改PasswordReset
以引用您的新ISender
服务:
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. 现在您不再需要担心传递任何东西,DI会为您处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.