【发布时间】:2023-03-08 13:30:02
【问题描述】:
我有一个 .net web api 核心项目,我会调用 microsoft graph
于是我创建了一个配置类:
public class GraphConfiguration
{
public static void Configure(IServiceCollection services, IConfiguration configuration)
{
//Look at appsettings.Development.json | https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1
var graphConfig = new AppSettingsSection();
configuration.GetSection("AzureAD").Bind(graphConfig);
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(graphConfig.ClientId)
.WithTenantId(graphConfig.TenantId)
.WithClientSecret(graphConfig.ClientSecret)
.Build();
ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphServiceClient = new GraphServiceClient(authenticationProvider);
}
}
在我的控制器中我有这个:
public class UserController : ControllerBase
{
private TelemetryClient telemetry;
private readonly ICosmosStore<Partner> _partnerCosmosStore;
private readonly GraphServiceClient _graphServiceClient;
// Use constructor injection to get a TelemetryClient instance.
public UserController(TelemetryClient telemetry,ICosmosStore<Partner> partnerCosmosStore, GraphServiceClient graphServiceClient)
{
this.telemetry = telemetry;
_partnerCosmosStore = partnerCosmosStore;
_graphServiceClient = graphServiceClient;
}
/// <summary>
/// Gets all partners
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult> GetUsers()
{
this.telemetry.TrackEvent("GetPartners");
try
{
var me = await _graphServiceClient.Me.Request().WithForceRefresh(true).GetAsync();
return Ok(me);
}
catch (Exception ex)
{
string guid = Guid.NewGuid().ToString();
var dt = new Dictionary<string, string>
{
{ "Error Lulo: ", guid }
};
telemetry.TrackException(ex, dt);
return BadRequest("Error Lulo: " + guid);
}
}
}
但我认为我在 Startupcs 中缺少一步。我如何实际将其注入所有控制器中?
【问题讨论】:
标签: c# .net asp.net-core dependency-injection asp.net-web-api2