Autofac - 注册插件

发布于 2024-09-28 07:49:02 字数 66 浏览 0 评论 0原文

我有一个定义了一些方法的接口,并且有 N 个实现它的类。如何使用 autofac 注册所有加载的程序集中找到的所有类?

i have an interface that defines some methods and i have N classes that implement it. How can i register all the classes found in all the loaded assemblies with autofac?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゝ杯具 2024-10-05 07:49:02

您必须“了解”包含类的程序集,您也许可以使用 Assembly.Load(..) 自己加载它们。

从那里,很容易注册类:

var assemblies = new[]{....};

builder.RegisterAssemblyTypes(assemblies) 
            .Where(t => typeof(IMyInterface).IsAssignableFrom(t)) 
            .As<IMyInterface>(); 

更新:要获取注册的实例,您可以使用 Autofac 对集合的内置支持:

public class MyService
{
    private readonly IEnumerable<IMyInterface> _services;
    public MyService(IEnumerable<IMyInterface> services)
    {
        _services = services;
    }

    public void DoStuffWithServices()
    {
        foreach(var svc in _services)
        {
           ...
        }
    }
}

You will have to "know about" the assemblies containing the classes, you could perhaps load them yourself with Assembly.Load(..).

From there, it is easy to register the classes:

var assemblies = new[]{....};

builder.RegisterAssemblyTypes(assemblies) 
            .Where(t => typeof(IMyInterface).IsAssignableFrom(t)) 
            .As<IMyInterface>(); 

Update: to get to the registered instances, you can use Autofac builtin support for collections:

public class MyService
{
    private readonly IEnumerable<IMyInterface> _services;
    public MyService(IEnumerable<IMyInterface> services)
    {
        _services = services;
    }

    public void DoStuffWithServices()
    {
        foreach(var svc in _services)
        {
           ...
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文