Skip to content

Commit

Permalink
Memory optimization from #919: Autofac.Builder.RegistrationBuilder<T,…
Browse files Browse the repository at this point in the history
…U,V>.
  • Loading branch information
tillig committed Aug 16, 2018
1 parent 0a3a081 commit 7641af7
Showing 1 changed file with 40 additions and 5 deletions.
Expand Up @@ -241,11 +241,32 @@ public RegistrationBuilder(Service defaultService, TActivatorData activatorData,
/// <returns>A registration builder allowing further configuration of the component.</returns>
public IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> As(params Type[] services)
{
return As(services.Select(t =>
t.FullName != null
? new TypedService(t)
: new TypedService(t.GetGenericTypeDefinition()))
.Cast<Service>().ToArray());
// Issue #919: Use arrays and iteration rather than LINQ to reduce memory allocation.
Service[] argArray = new Service[services.Length];
for (int i = 0; i < services.Length; i++)
{
if (services[i].FullName != null)
{
argArray[i] = new TypedService(services[i]);
}
else
{
argArray[i] = new TypedService(services[i].GetGenericTypeDefinition());
}
}

return As(argArray);
}

/// <summary>
/// Configure a single service that the component will provide.
/// </summary>
/// <param name="service">Service type to expose.</param>
/// <returns>A registration builder allowing further configuration of the component.</returns>
public IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> As(Type service)
{
// Issue #919: Avoid allocating the array for params if there's only one item.
return As(new TypedService(service));
}

/// <summary>
Expand All @@ -262,6 +283,20 @@ public RegistrationBuilder(Service defaultService, TActivatorData activatorData,
return this;
}

/// <summary>
/// Configure a single service that the component will provide.
/// </summary>
/// <param name="service">Service to expose.</param>
/// <returns>A registration builder allowing further configuration of the component.</returns>
public IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> As(Service service)
{
if (service == null) throw new ArgumentNullException(nameof(service));

RegistrationData.AddService(service);

return this;
}

/// <summary>
/// Provide a textual name that can be used to retrieve the component.
/// </summary>
Expand Down

0 comments on commit 7641af7

Please sign in to comment.