Skip to content

Instantly share code, notes, and snippets.

@robfe
Created April 6, 2018 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robfe/8ccc25dce2f27f1e2c4be7db65da0caa to your computer and use it in GitHub Desktop.
Save robfe/8ccc25dce2f27f1e2c4be7db65da0caa to your computer and use it in GitHub Desktop.
Register a set of POCOs to be read from IConfiguration in Autofac
public class SettingsRegistrationSource : IRegistrationSource
{
public string Suffix { get; }
public SettingsRegistrationSource(string suffix)
{
Suffix = suffix;
}
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
if (!(service is IServiceWithType swt))
{
return Enumerable.Empty<IComponentRegistration>();
}
var name = swt.ServiceType.Name;
if (!name.EndsWith(Suffix))
{
return Enumerable.Empty<IComponentRegistration>();
}
var settingsSectionName = name.Substring(0, name.Length - Suffix.Length);
var registration = new ComponentRegistration(
Guid.NewGuid(),
new DelegateActivator(swt.ServiceType, (c, p) =>
{
var config = c.Resolve<IConfiguration>();
return config.GetSection(settingsSectionName).Get(swt.ServiceType);
}),
new CurrentScopeLifetime(),
InstanceSharing.Shared,
InstanceOwnership.OwnedByLifetimeScope,
new[] {service},
new Dictionary<string, object>());
return new IComponentRegistration[] {registration};
}
public bool IsAdapterForIndividualComponents => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment