![](/img/trans.png)
[英]How to get Iconfiguration and IHostingenvironment in .net 4.7?
[英]How do I keep from having to pass around IConfiguration and IHostingEnvironment
我正在考虑重构和抽象一些代码以供学习。
我创建了此类:
using System;
namespace app.Classes
{
public class Emailer : ISender
{
public Emailer(IConfiguration config, IHostingEnvironment env)
{
}
...
}
然后我有另一个我想使用的课程:
namespace app.Notifications
{
public class PasswordReset : INotification
{
Emailer emailer = new Emailer();
public PasswordReset()
{
}
...
}
由于IConfiguration和IHostingEnvironment正在使用DI,因此在PasswordReset中实例化新的Emailer时如何避免将它们传递出去?
不应让PasswordReset
创建Emailer
的新实例,而应利用现有的DI并将Emailer
变成服务。
在Startup.cs
的ConfigureServices()
方法内,添加对Emailer
类的引用:
services.AddScoped<ISender, Emailer >();
然后更改PasswordReset
以引用您的新ISender
服务:
namespace app.Notifications
{
public class PasswordReset : INotification
{
private ISender _emailer;
public PasswordReset(ISender emailer)
{
_emailer = emailer;
}
...
}
现在您不再需要担心传递任何东西,DI会为您处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.