Код: Выделить всё
public class SharePointClient : ISharePointClient
{
private readonly SafeILogger _logger;
private readonly SharePointClientConfig _clientConfig;
private readonly GraphServiceClient _graphClient;
public SharePointClient(SafeILogger logger,
IOptions clientConfig)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_clientConfig = clientConfig.Value ?? throw new
ArgumentNullException(nameof(clientConfig));
_graphClient = GetAuthenticatedGraphClient();
}
Код: Выделить всё
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddSharePointUtils(this IServiceCollection services)
{
services.AddOptions()
.BindConfiguration("SharePointClientConfig")
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddScoped();
return services;
}
}
Код: Выделить всё
public class FileUploader : IFileUploader
{
private readonly ISharePointClient _sharePointClient;
public FileUploader(ISharePointClient sharePointClient)
{
_sharePointClient = sharePointClient ?? throw new
ArgumentNullException(nameof(sharePointClient));
}
public async Task UploadFile(string fileSourceFilePath, string fileName)
{
await _sharePointClient.UploadFileToDrive("TestPath",
"Test",
fileSourceFilePath, fileName);
}
}
Код: Выделить всё
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSafeILogger();
builder.Services.AddSharePointUtils();
builder.Services.AddScoped();
Код: Выделить всё
var services = new ServiceCollection();
services.AddSafeILogger();
services.AddScoped();
services.AddSharePointUtils();
var serviceProvider = services.BuildServiceProvider();
var fileUploader = serviceProvider.GetRequiredService();
«Невозможно разрешить службу для типа Microsoft.Extensions.Logging.ILogger».
Код: Выделить всё
1[Common.SharePoint.Utils.SharePointClient]' while attempting to activate 'Common.Api.Logging.SafeILogger
Метод AddSafeILogger() разрешает эту зависимость в проекте API, но ему не удается разрешить зависимость в Консольное приложение. Вот AddSafeILogger
Код: Выделить всё
namespace Common.Api.Logging;
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddSafeILogger(this IServiceCollection services)
{
services.TryAddSingleton(typeof(SafeILogger));
return services;
}
}
Я не уверен, почему реализация DI работает для приложения API, но в консольном приложении, когда я пытаюсь создать экземпляр FileUploader, вызвав метод GetRequiredService, я получаю упомянутую ошибку зависимости. DI для других пользовательских классов отлично работает в консольном приложении.
Подробнее здесь: https://stackoverflow.com/questions/791 ... pplication