Autofac Scanning Assemblies for certain class type

后端 未结 2 760
北荒
北荒 2020-12-15 08:39

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

相关标签:
2条回答
  • 2020-12-15 09:12

    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>>();
    
    0 讨论(0)
  • 2020-12-15 09:16

    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.

    0 讨论(0)
提交回复
热议问题