.NET Core Web API依赖注入时如何在其他类中使用自定义类及其功能
问题解决步骤
1. 修正字段类型不匹配问题
你在AdoExtract类中声明的依赖字段类型是Communication,但实际你要注入的是CommunicationApi类型,类型不一致自然无法访问到CommunicationApi的属性和方法,首先修改AdoExtract的字段定义:
public class AdoExtract : IAdoExtract { private readonly IConfiguration _configuration; private readonly ILogger _logger; // 把原来的Communication类型改为CommunicationApi private readonly CommunicationApi _com; public AdoExtract(ILogger<AdoExtract> logger, IConfiguration configuration = null, CommunicationApi com = null) { _configuration = configuration; _logger = logger; _com = com; } }
2. 补全CommunicationApi的依赖注册
CommunicationApi的构造函数要求注入Func<string, myAuthentication>类型的参数,你当前只注册了CommunicationApi本身,没有注册这个Func依赖,DI容器无法实例化CommunicationApi对象,需要在Startup的ConfigureServices中补充注册:
public void ConfigureServices(IServiceCollection services) { // 先注册Func<string, myAuthentication>的实现,根据你自己的myAuthentication逻辑调整 services.AddSingleton<Func<string, myAuthentication>>(sp => scopeName => { // 这里写你自己的myAuthentication实例化逻辑,比如从容器取对应服务初始化 return new myAuthentication(scopeName); }); // 再注册CommunicationApi services.AddScoped<CommunicationApi>(); // 别忘了注册你的AdoExtract服务 services.AddScoped<IAdoExtract, AdoExtract>(); }
3. 修正CommunicationApi构造函数的笔误
你构造函数的参数名为SAuth,但赋值时写的是mAuth,属于拼写错误,修正如下:
public CommunicationApi(ILogger<AdoExtract> logger, Func<string, myAuthentication> SAuth, IConfiguration configuration = null) { _configuration = configuration; _logger = logger; // 把原来的mAuth改为参数名SAuth _myAuthentication = SAuth("ApiGatewayScope"); }
4. 调用示例
做完以上修改后,你就可以在TestMail方法中正常访问CommunicationApi的属性和方法了:
public async Task<int> TestMail() { _com.MyMail = new myEmail() { // 赋值邮件标题、收件人、内容等属性 }; _com.Attachments = new string[] { "文件路径1", "文件路径2" }; _com.IsBodyHtml = true; // 调用发送邮件方法 return await _com.SendMail(); }
注意:如果你的Communication是你定义的接口,那你需要让CommunicationApi实现该接口,同时注册接口和实现的映射关系,注入时用接口类型即可,这种方案更符合依赖注入的最佳实践。
内容的提问来源于stack exchange,提问作者Sandeep Thomas
相关产品推荐
相关产品推荐

