Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac Scanning Assemblies for certain class type

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!!!!
like image 369
Jon Avatar asked Feb 06 '12 11:02

Jon


People also ask

Which of the following option is used in automatic types of registration in order to scan an assembly and automatically register its types by convention?

The real selling point for Scrutor is its methods to scan your assemblies, and automatically register the types it finds.

What is AsImplementedInterfaces?

AsImplementedInterfaces<TLimit>(IRegistrationBuilder<TLimit, ScanningActivatorData, DynamicRegistrationStyle>) Specifies that a type from a scanned assembly is registered as providing all of its implemented interfaces.

How do I register an Autofac interface?

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.


2 Answers

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>>();
like image 52
Jehof Avatar answered Oct 19 '22 03:10

Jehof


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.

like image 7
Wojteq Avatar answered Oct 19 '22 04:10

Wojteq