Autofac composite pattern

两盒软妹~` 提交于 2019-11-29 20:01:39

问题


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) { ... }
    ...
}

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)

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

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

Update:

My current registration is:

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

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

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

Can it be improved?


回答1:


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");

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

Now how to write it...




回答2:


You could try named or keyed registrations. A named registration simply gets a string name, to differentiate it from other registrations of the same interface. Similarly, a key uses some value type, for instance an enum, to discriminate between multiple registrations. Your CompositeService would likely be the default reference, registered by type with no other special info needed. You'll need some method to resolve the other IService dependencies and pass them to the constructor; a factory method for CompositeService may work.



来源:https://stackoverflow.com/questions/5092602/autofac-composite-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!