I've started using Autofac
and want to scan some DLL's and get Autofac
to register some of the classes within them.
The classes that I'm interested in all inherit from a PluginBase class but the below code doesn't seem to be registering them. Can anyone help?
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(assemblies)
.Where(t => t.BaseType == typeof(PluginBase))
.AsImplementedInterfaces()
.AsSelf();
var container = builder.Build();
var pluginClasses = container.Resolve<IEnumerable<PluginBase>>();
//pluginClasses is empty!!!!
The real selling point for Scrutor is its methods to scan your assemblies, and automatically register the types it finds.
AsImplementedInterfaces<TLimit>(IRegistrationBuilder<TLimit, ScanningActivatorData, DynamicRegistrationStyle>) Specifies that a type from a scanned assembly is registered as providing all of its implemented interfaces.
Register by Type var builder = new ContainerBuilder(); builder. RegisterType<ConsoleLogger>(); builder. RegisterType(typeof(ConfigReader)); When using reflection-based components, Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container.
I think you need to specify the base class of your Plugins on registration. The call AsImplementedInterfaces registers the type with its implemented interfaces and not by its base type. You should update your registration to register your plugins as PluginBase.
Here´s the code:
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(assemblies)
.Where(t => t.BaseType == typeof(PluginBase))
.As<PluginBase>();
var container = builder.Build();
var pluginClasses = container.Resolve<IEnumerable<PluginBase>>();
Maybe do is this way:
builder
.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t => t.GetInterfaces()
.Any(i => i.IsAssignableFrom(typeof (IDependency))))
.AsImplementedInterfaces()
.InstancePerDependency();
In this code I use IDependency
as a marker interface. You may replace it with your PluginBase
class and remove Where
method.
The point is to use IsAssignableFrom
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With