在ASP.NET Core应用程序中使用AddScoped时,可能会遇到需要调用正确的构造函数来实例化服务的情况。为此,可以使用泛型委托来指定使用哪个构造函数。
例如,下面的代码片段中,UserService需要实例化UserRepository和EmailService,其中UserRepository需要一个IOptions
public interface IUserRepository
{
// ...
}
public class UserRepository : IUserRepository
{
public UserRepository(IOptions userOptions)
{
// ...
}
// ...
}
public interface IEmailService
{
// ...
}
public class EmailService : IEmailService
{
public EmailService(IOptions emailOptions)
{
// ...
}
// ...
}
public class UserService
{
private readonly IUserRepository _userRepository;
private readonly IEmailService _emailService;
private readonly ILogger _logger;
public UserService(IUserRepository userRepository, IEmailService emailService, ILogger logger)
{
_userRepository = userRepository;
_emailService = emailService;
_logger = logger;
}
// ...
}
为了正确地实例化UserService,可以使用AddScoped方法,并使用泛型委托来指定使用哪个构造函数:
services.AddScoped(sp =>
{
var userRepository = sp.GetService();
var emailService = sp.GetService();
var logger = sp.GetService>();
return new UserService(userRepository, emailService, logger);
});
这将告诉ASP.NET Core容器,当需要UserService实例时,应使用上面定义的委托。该委托获取IUserRepository、IEmailService和ILogger
然后,在控制器或其他地方使用注入的UserService