特定类类型的 Autofac 扫描程序集 [英] Autofac Scanning Assemblies for certain class type

查看:24
本文介绍了特定类类型的 Autofac 扫描程序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用 Autofac 并想扫描一些 DLL 并让 Autofac 注册其中的一些类.

I've started using Autofac and want to scan some DLL's and get Autofac to register some of the classes within them.

我感兴趣的类都继承自 PluginBase 类,但下面的代码似乎没有注册它们.有人可以帮忙吗?

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

推荐答案

我认为您需要在注册时指定插件的基类.调用 AsImplementedInterfaces 使用其实现的接口而不是基类型来注册类型.您应该更新您的注册以将您的插件注册为 PluginBase.

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.

代码如下:

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

这篇关于特定类类型的 Autofac 扫描程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆