简体   繁体   English

如何避免必须传递IConfiguration和IHostingEnvironment

[英]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.csConfigureServices()方法内,添加对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.

相关问题 如何在.net 4.7中获取Iconfiguration和IHostingenvironment? - How to get Iconfiguration and IHostingenvironment in .net 4.7? 如何使用 Moq 模拟 IConfiguration? - How do I mock IConfiguration with Moq? 如何在我的 DbContext 中获取 IConfiguration 实例? - How do I get an IConfiguration instance in my DbContext? 如何避免每次回发后页面跳动? - How do I keep my page from jumping around after every postback? 如何将IConfiguration绑定到构造函数中具有参数的类 - How to bind IConfiguration to class having parameters in constructor 如何从ASP.NET Core中的DbContext获取IHostingEnvironment - How can I get IHostingEnvironment from DbContext in ASP.NET Core 如何保持2个对象之间具有相互依赖性的不变性 - how do I keep immutability having a mutual dependency between 2 objects 在使用BeginInvoke和EndInvoke时,如何避免传递/存储委托? - How can I avoid having to pass around/store a delegate when using BeginInvoke and EndInvoke? docker 将环境变量写入IConfiguration,怎么办? - docker compose environment variable to IConfiguration, how to do? 如何在本地创建IConfiguration实例? - How can I create an instance of IConfiguration locally?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM