为多个接口返回相同的实例

jga*_*fin 32 c# singleton autofac

我正在使用以下代码注册组件:

StandardKernel kernel = new StandardKernel();

string currentDirectory = Path.GetDirectoryName(GetType().Assembly.Location)
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
    if (!Path.GetDirectoryName(assembly.Location).Equals(currentDirectory)) 
        continue;

    foreach (var type in assembly.GetTypes())
    {
        if (!type.IsComponent()) 
            continue;

        foreach (var @interface in type.GetInterfaces())
        kernel.Bind(@interface).To(type).InSingletonScope();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个实现两个接口的类:

class StandardConsole : IStartable, IConsumer<ConsoleCommand>
Run Code Online (Sandbox Code Playgroud)

如果我解决了IStartable我得到一个实例,如果我解决IConsumer<ConsoleCommand>我得到另一个.

如何为两个接口获取相同的实例?

Nic*_*rdt 71

builder.RegisterType<StandardConsole>()
   .As<IStartable>()
   .As<IConsumer<ConsoleCommand>>()
   .SingleInstance();
Run Code Online (Sandbox Code Playgroud)

Autofac非常广泛使用的功能 - 任何问题然后有一个错误:)

Hth Nick

编辑通过它的外观,你在As()的重载之后采用IEnumerable <Type>() - 使用IntelliSense检查所有的As()重载,这应该适合你的场景.正如另一位评论者指出的那样,您需要使用所有信息更新问题.

  • 我知道你的意思(我写的;)) - 我建议的那个是不同的.如果您有一个要公开的接口列表(i1,i2,i3 ..),您可以将整个列表传递给单个As()调用.您还可以查看RegisterAssemblyTypes(myAsm).AsImplementedInterfaces(),它可以扩展为您的文章提出的建议http://code.google.com/p/autofac/wiki/Scanning - 欢迎您通过如果您愿意,可以通过Autofac论坛进行讨论. (2认同)