Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private void RegisterFromServiceCollection_Old(IServiceCollection services)
- {
- var serviceProvider = services.BuildServiceProvider();
- var servicesToRegister = new Dictionary<Type, (HashSet<Type> contractTypes, ServiceLifetime lifetime)>();
- var delegateType = typeof(Delegate);
- foreach (var service in services)
- {
- if (delegateType.IsAssignableFrom(service.ServiceType))
- {
- Debug.Log($"Skipping type registration, because of delegate registration: {service.ServiceType}. Register this type manually");
- continue;
- }
- Type actualImplementationType;
- if (!(service.ImplementationType is null))
- {
- actualImplementationType = service.ImplementationType;
- }
- else if (!(service.ImplementationFactory is null))
- {
- actualImplementationType = serviceProvider.GetService(service.ServiceType).GetType();
- }
- else
- {
- actualImplementationType = service.ServiceType;
- }
- if (servicesToRegister.TryGetValue(actualImplementationType, out var registeredContracts))
- {
- if (registeredContracts.lifetime != service.Lifetime)
- {
- throw new NotSupportedException(
- "Mismatching lifetimes for a type implementing multiple interfaces is not supported. "
- + $"Service type: {service.ServiceType}. "
- + $"First registered lifetime: {registeredContracts.lifetime}. "
- + $"Lifetime when trying to register: {service.Lifetime}");
- }
- registeredContracts.contractTypes.Add(service.ServiceType);
- }
- else
- {
- servicesToRegister.Add(actualImplementationType, (new HashSet<Type> { service.ServiceType }, service.Lifetime));
- }
- }
- foreach (var serviceWithContracts in servicesToRegister)
- {
- var binding = Container.Bind(serviceWithContracts.Value.contractTypes).To(serviceWithContracts.Key);
- switch (serviceWithContracts.Value.lifetime)
- {
- case ServiceLifetime.Singleton:
- binding.AsSingle();
- break;
- case ServiceLifetime.Scoped:
- binding.AsCached();
- break;
- case ServiceLifetime.Transient:
- binding.AsTransient();
- break;
- default:
- throw new ArgumentOutOfRangeException($"Unknown service lifetime{serviceWithContracts.Value.lifetime}");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement