为“A”类型的每个实例解析类型为“B”的实例

时间:2014-08-19 13:43:21

标签: ioc-container autofac

我有一个名为规范的接口:

public interface ISpecification { ... }

我的应用程序中可能存在许多此实现,而且我还有一个需要规范的处理器:

public interface IProcessor { ... }

public class Processor : IProcessor
{
    public Processor (ISpecification specification) { ... }
}

我使用Autofac(版本3.5.2)作为我的IOC容器,我希望能够调用:

var processors = container.Resolve<IEnumerable<IProcessor>>();

为每个已注册的IProcessor返回一个ISpecification,这可能吗?

1 个答案:

答案 0 :(得分:3)

这听起来像Autofac的Adapters

  

Autofac提供内置适配器注册,因此您可以注册   一组服务,并让它们各自自动适应一个   不同的界面。

var builder = new ContainerBuilder();

// Register the services to be adapted
builder.RegisterType<SaveCommand>()
       .As<ICommand>()
       .WithMetadata("Name", "Save File");
builder.RegisterType<OpenCommand>()
       .As<ICommand>()
       .WithMetadata("Name", "Open File");

// Then register the adapter. In this case, the ICommand
// registrations are using some metadata, so we're
// adapting Meta<ICommand> instead of plain ICommand.
builder.RegisterAdapter<Meta<ICommand>, ToolbarButton>(
   cmd =>
    new ToolbarButton(cmd.Value, (string)cmd.Metadata["Name"]));

var container = builder.Build();

// The resolved set of buttons will have two buttons
// in it - one button adapted for each of the registered
// ICommand instances.
var buttons = container.Resolve<IEnumerable<ToolbarButton>>();