适用于某些类别类型的 Autofac 扫描组件
我已经开始使用 Autofac 并希望扫描一些 DLL 并让 Autofac 注册其中的一些类。
我感兴趣的类都继承自 PluginBase 类,但下面的代码似乎没有注册它们。有人可以帮忙吗?
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!!!!
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!!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您需要在注册时指定插件的基类。调用 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.
Here´s the code:
也许是这样的:
在这段代码中,我使用
IDependency
作为标记接口。您可以将其替换为PluginBase
类并删除Where
方法。重点是使用
IsAssignableFrom
方法。Maybe do is this way:
In this code I use
IDependency
as a marker interface. You may replace it with yourPluginBase
class and removeWhere
method.The point is to use
IsAssignableFrom
method.请注意,由于与重新启动 IIS 相关的问题,您不应使用
AppDomain.CurrentDomain.GetAssemblies()
。要避免此问题,请使用 GetReferencedAssemblies()< 方法rel="nofollow noreferrer">System.Web.Compilation.BuildManager 来获取引用的程序集的列表:
这将强制引用的程序集立即加载到
AppDomain
中可用于模块扫描。有关更多详细信息,您可以在这里阅读: https://autofac.readthedocs .io/en/latest/faq/iis-restart.html
Pls, note that you shouldn't use
AppDomain.CurrentDomain.GetAssemblies()
due to an issue related to restarting IIS.To avoid this issue use the GetReferencedAssemblies() method on System.Web.Compilation.BuildManager to get a list of the referenced assemblies instead:
That will force the referenced assemblies to be loaded into the
AppDomain
immediately making them available for module scanning.For more detail, you can read here: https://autofac.readthedocs.io/en/latest/faq/iis-restart.html