Skip to content

Instantly share code, notes, and snippets.

@Rene-Sackers
Created July 27, 2018 12:41
Show Gist options
  • Save Rene-Sackers/6da12c9a0b1676e13f0cea6d4b91c8a0 to your computer and use it in GitHub Desktop.
Save Rene-Sackers/6da12c9a0b1676e13f0cea6d4b91c8a0 to your computer and use it in GitHub Desktop.
Autofac NotAssignableTo extension

Can be used for issue with AutoFac where assembly scanning is used, and IStartables are ran twice:

builder.RegisterAssemblyTypes(GetType().Assembly)
	.InNamespaceOf<SettingsProvider>()
	.NotAssignableTo<IStartable>()
	.AsImplementedInterfaces();

builder.RegisterAssemblyTypes(GetType().Assembly)
	.InNamespaceOf<SettingsProvider>()
	.AssignableTo<IStartable>()
	.AsImplementedInterfaces()
	.SingleInstance();
public static class RegistrationBuilderExtensions
{
public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle> NotAssignableTo<T>(this IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle> registration)
{
return registration.NotAssignableTo(typeof(T));
}
public static IRegistrationBuilder<TLimit, TScanningActivatorData, TRegistrationStyle> NotAssignableTo<TLimit, TScanningActivatorData, TRegistrationStyle>(this IRegistrationBuilder<TLimit, TScanningActivatorData, TRegistrationStyle>
registration, Type type) where TScanningActivatorData : ScanningActivatorData
{
if (registration == null)
throw new ArgumentNullException(nameof(registration));
registration.ActivatorData.Filters.Add(t => !type.GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()));
return registration;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment