Autofac复合模式 [英] Autofac composite pattern

查看:38
本文介绍了Autofac复合模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到我经常需要实现复合模式.例如:

I noticed I quite often need to implement composite pattern. For example:

interface IService { ... }
class Service1 : IService { ... }
class Service2 : IService { ... }
class CompositeService : IService
{
    public CompositeService(IEnumerable<IService> services) { ... }
    ...
}

我想在容器中将 CompositeService 注册为 IService 并注入依赖项.

I want to register CompositeService as IService in container and have dependencies injected.

(看起来有点像装饰器,但装饰的是一组服务而不是一个)

(looks somewhat similar to Decorator but decorating set of services instead of only one)

在 autofac 中最好的方法是什么?

What's the best way to do it in autofac?

理想的解决方案是怎样的(对于 C#)?

How would ideal solution look like (for C#)?

更新:

我目前的注册是:

builder.RegisterType<Service1>().Named<IService>("impl");
builder.RegisterType<Service2>().Named<IService>("impl");

builder.Register(c => new CompositeService(c.Resolve<IEnumerable<IService>>("impl")))
    .As<IService>();

它类似于http://nblumhardt.com/2011/01/decorator-support-in-autofac-2-4

It is similar to Decorators by Hand in http://nblumhardt.com/2011/01/decorator-support-in-autofac-2-4

可以改进吗?

推荐答案

我还没有实现这个,甚至没有完全考虑过,但我能实现的最好的语法是:

I haven't implemented this or even thought it through fully, but the best syntax I could achieve is:

builder
.RegisterComposite<IService>((c, elements) => new CompositeService(elements))
.WithElementsNamed("impl");

注册函数的elements参数将是IEnumerable类型并封装c.Resolve>("impl").

The elements parameter to the registration function would be of type IEnumerable<IService> and encapsulate the c.Resolve<IEnumerable<IService>>("impl").

现在怎么写...

这篇关于Autofac复合模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆