如何在以下情况下使用Autofac实现装饰器模式

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

我需要使用Autofac实现装饰器模式。

我有两个具有各自实现的类/服务。现在,基于条件,我需要能够动态调用任何一个服务类以获取数据。

ServiceClassA : InterfaceA 
{
   // Method A
}

ServiceClassB : InterfaceB
{
  //Method B
}

目前,我已经注册了如下所示的ServiceClassA和ServiceClassB

builder.RegisterType<ServiceClassA>()
       .WithParameter( new resolvedParameter())
       .As<InterfaceA>()
       .InstancePerLifeTimeScope();

builder
       .RegisterType<ServiceClassB>()
       .As<InterfaceB>()
       .InstancePerLifetimeScope();

如下所示,从控制器(ControllerClass)内部调用ServiceClassA

ControllerClass : Controller 
{
  private readonly InterfaceA _serviceClassA;
  public Controller(Interface serviceClassA)
  {
    _serviceClassA = serviceClassA;
  }

  public ActionResult Get()
  {
   var obj = _serviceClassA.MethodA();
  }
}

进行上述调用时,应根据条件(日期> 2020年3月31日),调用ServiceClassB中的方法B。为此,我们的技术架构师认为Autofac的装饰器模式是对现有代码流影响很小的解决方案。

所以我对ServiceClassA注册进行了以下更改

builder.RegisterType<ServiceClassA>()
           .WithParameter( new resolvedParameter())
           .Named<InterfaceA>("serviceClassA")
           .InstancePerLifeTimeScope();
 builder.RegisterDecorator<InterfaceA>(
            (c,serviceClassA) => ServiceDecorator(), 
            "serviceClassA");

在上述步骤之后,我被困住了,不知道在哪里应用该条件。检查了许多关于stackoverflow的答案,以找到无法解决的解决方案。

c# asp.net-mvc autofac decorator-pattern
1个回答
0
投票

装饰器模式依赖于两个类实现相同的Interface。并非如上所述。 E. G。

public interface IProductRepository
{
  Product Get(int id);
}

public class ProductRepository : IProductRepository
{
  public Product Get(string id)
  {
    // logic to get product
  } 
}

public class LoggingProductRepository : IProductRepository
{
  private IProductRepository _productRepository;
  private ILog _logger;

  public LoggingProductRepository(IProductRepository productRepository, ILog logger) 
  {
    _productRepository = productRepository;
    _logger = logger;
  } 

  public Product Get(string id) 
  {
     _logger.Log("something");
     return _productRepository.Get(id);
  } 
} 
© www.soinside.com 2019 - 2024. All rights reserved.