Open torfig opened 2 years ago
Did you find a solution for this? I've run into the same issue with named registrations.
Did you find a solution for this? I've run into the same issue with named registrations.
I don't know if this works when using builder.OverrideService()...., but generally this is what work's for us:
/// <summary>
/// Registers the given instance with the given namen and removes the last already available registration for this type and with this name.
/// </summary>
/// <param name="instance">The instance which should be registered with the given name.</param>
/// <param name="name">The name of the registration.</param>
/// <typeparam name="TType">The type of the given instance.</typeparam>
/// <param name="serviceRegistry">The service registry is needed to remove already existing registrations.</param>
public static TType OverrideNamed<TType>(this TType instance, string name, ServiceRegistry serviceRegistry) where TType : Instance
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException(@"Value cannot be null or whitespace.", nameof(name));
if (serviceRegistry == null)
throw new ArgumentNullException(nameof(serviceRegistry));
serviceRegistry.RemoveAll(serviceDescriptor => serviceDescriptor.ServiceType == instance.ServiceType && serviceDescriptor.ImplementationInstance is Instance currentInstance && currentInstance.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
instance.Named(name);
return instance;
}
I'm using Lamar for DI and the
IHostBuilder.OverrideServices
method to introduce fakes/mocks during integration testing which works fine until I want to replace a named instance.As soon as I add a named instance in OverrideServices that is already registered elsewhere, I get the following error:
I'm unsure if this has any relevance, but we're using a policy to reference the correct registered name when resolving the
IDbRepository
(and use an Attribute on theIDbRepository
parameter to specify the name to resolve to)I'm using the latest version of Lamar (8.0.1) and asp.net core 6.0.
This same error occurs if I register the same type with the same name twice. Any ideas how to resolve this? Maybe I could remove the previous named registration somehow (I'd need a way to do that within the OverrideServices method)?