Autofac Scanning Assemblies for certain class type

人盡茶涼 提交于 2019-11-27 14:49:06

问题


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 registerting 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!!!!

回答1:


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>>();



回答2:


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.



来源:https://stackoverflow.com/questions/9159277/autofac-scanning-assemblies-for-certain-class-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!