Как преобразовать RegisterDecorator из Simple Injector в IServiceCollection .NET Core?C#

Место общения программистов C#
Anonymous
Как преобразовать RegisterDecorator из Simple Injector в IServiceCollection .NET Core?

Сообщение Anonymous »

Я пытаюсь перенести некоторый код из шаблона RegisterDecorator Simple Injector, который находится в .Net Framework, в IServiceCollection .NET Core. В Simple Injector мой код выглядит так:

Код: Выделить всё

container.Register(Lifetime.Singleton);
container.RegisterDecorator(typeof(IContentGetHandler), typeof(RemoveUnsupportedFields), Lifetime.Singleton);
container.RegisterDecorator(typeof(IContentGetHandler), typeof(LoadContentBaseFields), Lifetime.Transient);
container.RegisterDecorator(typeof(IContentGetHandler), typeof(AddFieldsWithoutValues), Lifetime.Transient);
container.RegisterDecorator(typeof(IContentGetHandler), typeof(SetCalcFieldErrors), Lifetime.Transient);
container.RegisterDecorator(typeof(IContentGetHandler), typeof(HandleAssembleException), Lifetime.Transient);
Я попытался преобразовать это в IServiceCollection с помощью следующего метода:

Код: Выделить всё

public void RegisterDecorator(Type serviceType, Type decoratorType, Lifetime lifeTime)
{
var serviceDescriptor = _services.FirstOrDefault(descriptor => descriptor.ServiceType == serviceType);
if (serviceDescriptor == null)
{
throw new InvalidOperationException($"Service of type {serviceType.Name} not registered.");
}

if (serviceDescriptor.ImplementationType == null)
{
_services.Remove(serviceDescriptor);
}

_services.Add(new ServiceDescriptor(serviceType, decoratorType, MapLifetime(lifeTime)));
}
Я вижу, что экземпляры создаются в коллекции сервисов, но когда я выполняю serviceLocator.getRequiredService(); он выдает исключение как проблему циклической зависимости.
Я сталкиваюсь с проблемами при этом подходе и не понимаю, почему он не работает должным образом. В частности:
  • Как правильно зарегистрировать декораторы в системе DI .NET Core?
  • Есть ли лучший способ обрабатывать удаление и повторное добавление служб при использовании декораторов с IServiceCollection?
  • Как лучше всего обеспечить правильный порядок выполнения этих декораторов в .NET Core?
    Будем очень признательны за любую помощь или идеи!

    Подробнее здесь: https://stackoverflow.com/questions/790 ... servicecol

Вернуться в «C#»