我想通过
IConfiguration
访问秘密,我在 Program.cs
中这样设置:
namespace Project
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Configuration
.AddJsonFile("secrets.json");
builder.Services.AddSingleton<IConfiguration>(builder.Configuration);
var app = builder.Build();
...
app.Run();
}
}
}
但是当我尝试从另一个类访问它时
configuration
为空:
using Amazon.S3;
using Amazon.S3.Model;
namespace Project.Services
{
public class S3Service
{
private static IConfiguration configuration;
public S3Service(IConfiguration _configuration)
{
configuration = _configuration;
}
}
}
首先您需要为 S3Service 创建一个接口,然后在 S3Service 中实现该接口,然后在
program.cs
文件中注册您的 S3Service,如下所示:
1。创建界面
public interface IS3Service
{
public bool UploadFileToS3(string filePath); // Example interface method
}
2。实现接口
public class S3Service : IS3Service // <- Add this
{
private static IConfiguration _configuration;
}
public S3Service(IConfiguration configuration)
{
_configuration = configuration;
}
public bool UploadFileToS3(string filePath)
{
// Upload File to S3 implementation
}
3.将
S3Service
注册到 program.cs
文件中
builder.Services.AddTransient<IS3Service, S3Service>();
完成后,您应该能够获取配置值。 尝试一下,让我知道效果如何。