Autofac - 获取所有实现特定接口的接口的类的实例
创始人
2024-09-23 00:31:39
0

在使用 Autofac 进行依赖注入时,可以使用 IEnumerable 来获取所有实现特定接口的类的实例。下面是一个示例代码:

using Autofac;
using System;
using System.Collections.Generic;

public interface IMyInterface
{
    void DoSomething();
}

public class MyClass1 : IMyInterface
{
    public void DoSomething()
    {
        Console.WriteLine("MyClass1 DoSomething");
    }
}

public class MyClass2 : IMyInterface
{
    public void DoSomething()
    {
        Console.WriteLine("MyClass2 DoSomething");
    }
}

public class MyClass3 : IMyInterface
{
    public void DoSomething()
    {
        Console.WriteLine("MyClass3 DoSomething");
    }
}

public class MyClassConsumer
{
    private readonly IEnumerable _myClasses;

    public MyClassConsumer(IEnumerable myClasses)
    {
        _myClasses = myClasses;
    }

    public void UseMyClasses()
    {
        foreach (var myClass in _myClasses)
        {
            myClass.DoSomething();
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var builder = new ContainerBuilder();

        builder.RegisterType().As();
        builder.RegisterType().As();
        builder.RegisterType().As();
        builder.RegisterType();

        using (var container = builder.Build())
        {
            var consumer = container.Resolve();
            consumer.UseMyClasses();
        }
    }
}

在这个示例中,我们定义了一个 IMyInterface 接口和三个实现类。我们使用 Autofac 的 RegisterType 方法将这些实现类注册到容器中,并使用 As() 指定它们都实现了 IMyInterface 接口。

然后,我们通过 IEnumerable 将容器中所有实现了 IMyInterface 接口的类的实例注入到 MyClassConsumer 类中。

最后,在 Main 方法中,我们使用 container.Resolve() 获取 MyClassConsumer 类的实例,并调用其中的 UseMyClasses 方法,遍历并使用了所有实现了 IMyInterface 接口的类的实例。

相关内容

热门资讯

关于!微信微乐自建房辅助工具,... 关于!微信微乐自建房辅助工具,微乐家乡麻将自建房辅助app(开挂自建房)方法1)微乐家乡麻将自建房辅...
大家学习交流!微信卡五星辅助器... 大家学习交流!微信卡五星辅助器,微乐小程序免费黑科技(开挂自建房)方法1、很好的工具软件,可以解锁游...
三分钟了解!微乐微信自建房辅助... 三分钟了解!微乐微信自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)工具1、三分钟了解...
一分钟教会你!微乐家乡麻将自建... 一分钟教会你!微乐家乡麻将自建房辅助app,微乐自建房脚本免费入口(开挂自建房)方法1、用户打开应用...
分享实测!微信微乐自建房辅助工... 分享实测!微信微乐自建房辅助工具,微乐自建房脚本免费入口(开挂自建房)器1、起透看视 微信微乐自建房...
重大通报!微乐自建房辅助工具脚... 重大通报!微乐自建房辅助工具脚本,微乐小程序免费黑科技(开挂自建房)app微乐自建房辅助工具脚本破解...
如何分辨真伪!微乐微信自建房辅... 如何分辨真伪!微乐微信自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)技巧1、微乐微信自建房辅...
我来教教你!微乐自建房辅助工具... 我来教教你!微乐自建房辅助工具挂,微乐家乡麻将自建房辅助app(开挂自建房)工具1、玩家可以在微乐家...
重大来袭!微乐自建房辅助工具神... 重大来袭!微乐自建房辅助工具神器,微乐小程序免费黑科技(开挂自建房)器1、游戏颠覆性的策略玩法,独创...
带你了解!微信卡五星辅助器,微... 带你了解!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)方法1、带你了解!微信卡五星辅助器,...