初始化对象,不推入参数



我有一个带构造函数的类,用于记录和访问配置:

public class SendEmaiServiceProvider
{
private readonly IConfiguration _config;
private readonly IWebHostEnvironment _env;
private readonly ILogger<SendEmaiServiceProvider> _logger;
private readonly string _fromEmailAddress;

public SendEmaiServiceProvider(IConfiguration config, IWebHostEnvironment env, ILogger<SendEmaiServiceProvider> logger)
{
_config = config;
_env = env;
_logger = logger;
_fromEmailAddress = _config.GetValue<string>("AppSettings:Email:FromEmailAddress");
}
public void SayHi()
{
Console.WriteLine("Hi");
}
}

问题是-如何从另一个类调用方法SayHi而不推入logger,envconfig?

不,我用参数初始化新对象,但我确定这是错误的:

var sendEmaiServiceProvider = new SendEmaiServiceProvider(_config, _env, _logger);
sendEmaiServiceProvider.SayHi();

我可以创建一个空的构造函数,但我不会有_fromEmailAddress值。

看起来这是一个核心网站。如果是这样,则:

  1. 为依赖项创建一个interface
  2. Startup.cs
  3. 中注册依赖项
  4. 根据需要从netcore DI请求依赖项
public interface ISendEmaiServiceProvider
{
void SayHi()
}
public class SendEmaiServiceProvider : ISendEmaiServiceProvider
{
public void SayHi() { }
}

然后在Startup.cs中:

public void ConfigureServices( IServiceCollection services )
{
services.AddScoped<ISendEmaiServiceProvider, SendEmaiServiceProvider>();
}

然后在控制器中(或其他使用DI的地方),在.ctor中请求它,SendEmaiServiceProvider的所有依赖项将由DI自动填充。

public class HomeController : Controller
{
public readonly ISendEmaiServiceProvider _emailService;
public HomeController( ISendEmaiServiceProvider emailService )
{
_emailService = emailService
}
}

那应该能让你走了。

这里应该使用依赖注入。最好在这里创建一个接口,并在启动时解析你的'SendEmaiServiceProvider'。然后使用该接口,而不是为SayHi()方法创建一个新实例。

public interface YourInterface
{
void SayHi()
}
public class SendEmaiServiceProvider : YourInterface
{
public void SayHi() 
{ 
//your code
}
}

启动时,

public void ConfigureServices( IServiceCollection services )
{
services.AddScoped<YourInterface, SendEmaiServiceProvider>();
}

在控制器/服务上,

public class YourController : Controller
{
public readonly YourInterface _emailSenderService;

public HomeController( YourInterface emailSenderService )
{
_emailSenderService = emailSenderService
}



public IActionResult SayHI()    
{
_emailSenderService.SayHi()
}    
}

相关内容

  • 没有找到相关文章

最新更新