Autofac:如何装饰实现多个服务的单个组件

问题描述 投票:0回答:1

假设我有一个实现多个接口的组件:

public interface IService1 { }
public interface IService2 { }
public interface IService3 { }
public interface ICommonService : IService1, IService2, IService3 { }
public class CoreComponent : ICommonService { }

及其装饰器

public class DecoratorComponent : ICommonService
{
    public DecoratorComponent(ICommonService coreComponent) { }
}

然后我还需要解析 IService1-3 和 ICommonService 的实例。 这就是问题所在。

因为我想要有一个 CoreComponent 的单个实例和一个装饰器的单个实例。但读完这个问题我明白这是不可能的(据我所知)。

至少,我希望有一个 CoreComponent 的单个实例和多个装饰器实例(与服务一样多),装饰该单个核心组件实例。 但是当我将它们注册为以下

builder
    .RegisterType<CoreComponent>()
    .As<ICommonService>()
    .As<IService1>()
    .As<IService2>()
    .As<IService3>()
    .SingleInstance();
builder.RegisterDecorator<DecoratorService, ICommonService>();
builder.RegisterDecorator<DecoratorService, IService1>();
builder.RegisterDecorator<DecoratorService, IService2>();
builder.RegisterDecorator<DecoratorService, IService3>();

并解析IService1,我得到了一个装饰器的实例,装饰了一个装饰器的实例,装饰了一个核心组件的实例。这真令人沮丧。

如何正确注册该装饰器,以便在我的情况下只有一层装饰器,并解决所有服务?

c# decorator autofac
1个回答
0
投票

您可以将其注册为仅公开为

CoreComponent
,并为其他接口添加注册,将其转发到
IService1
分辨率,而不是将其注册为
IService2
IService3
ICommonService
ICommonService

最后,无论您从哪个接口解析 
var builder = new ContainerBuilder(); // Register the type as singleton builder .RegisterType<CoreComponent>() .As<ICommonService>() .SingleInstance(); // Register the decorator only once, for ICommonService. builder .RegisterDecorator<DecoratorService, ICommonService>(); // Now, forward service resolution to ICommonService builder .Register(container => container.Resolve<ICommonService>()) .As<IService1>() .As<IService2>() .As<IService3>();

CoreComponent
或任何
ICommonService
),Autofac 始终会从
IServiceX
注册中解析它,该注册由
ICommonService
装饰。
希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.