【问题标题】:ASP.NET Core access other services using dependency injectionASP.NET Core 使用依赖注入访问其他服务
【发布时间】:2017-07-29 11:43:58
【问题描述】:

这是一个 ASP.NET Core 默认项目ConfigureServices 方法:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc();

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

我的问题是如何访问 ApplicationDbContext 中的电子邮件服务或短信服务?

或者假设我将构建一个自定义服务,并像这样在 DI 中注册它:

services.AddTransient<ICustomService, CustomService>();

我如何在其中访问电子邮件服务或短信服务?

我假设必须先将电子邮件和短信服务添加到 DI,然后才能使用它们,对吗?

【问题讨论】:

    标签: c# dependency-injection asp.net-core


    【解决方案1】:

    ASP.NET Core 提供的默认 DI 实现仅支持构造函数注入。您的 CustomService 类应该有 ctor 期望依赖项(SMS/电子邮件发件人)作为参数:

    public class CustomService : ICustomService
    {
        public ClassName(IEmailSender emailSender, ISmsSender smsSender)
        {
            // use senders here or store in private variables
        }
    }
    

    定义构造函数时,请注意(来自Constructor Injection Behavior 部分)

    • 构造函数注入要求相关构造函数是公开的。
    • 构造函数注入要求只存在一个适用的构造函数。支持构造函数重载,但只能存在一个重载,其参数都可以通过依赖注入来实现。
    • 构造函数可以接受依赖注入未提供的参数,但这些参数必须支持默认值。

    我假设必须先将电子邮件和短信服务添加到 DI,然后才能使用它们的其他服务,对吗?

    它们应该在 DI 容器中注册,然后它才会尝试构造期望它作为构造函数参数的类的第一个实例。 由于方法services.AddTransient&lt;ICustomService, CustomService&gt;(); 没有实例化CustomService 类,下面它仍然是一个有效的代码:

    services.AddTransient<ICustomService, CustomService>();
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
    

    但是按照从简单到复杂的顺序进行注册是一个好习惯。

    【讨论】:

      猜你喜欢
      • 2017-08-26
      • 2021-11-28
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多