Created
April 6, 2018 11:49
-
-
Save robfe/8ccc25dce2f27f1e2c4be7db65da0caa to your computer and use it in GitHub Desktop.
Register a set of POCOs to be read from IConfiguration in Autofac
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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