具有参数化构造函数的 WCF 服务

WCF Service with parameterized constructor

我正在使用 .NET 4.5、C#.NET、WCF 存储库模式

WCF 服务

实施类

public class CustomerService : Service<Customer>, ICustomerService.cs
{
   private readonly IRepositoryAsync<Customer> _repository;
   public CustomerService(IRepositoryAsync<Customer> repository)
   {
      _repository = repository;
   }
}

public class OrdersService : Service<Orders>, IOrdersService.cs
{
   private readonly IRepositoryAsync<Order> _repository;
   public OrdersService(IRepositoryAsync<Order> repository)
   {
      _repository = repository;
   }
}

public class SalesService : Service<Sales>, ISalesService.cs
{
   private readonly IRepositoryAsync<Sales> _repository;
   public SalesService(IRepositoryAsync<Sales> repository)
   {
      _repository = repository;
   }
}

当我 运行 我的 WCF 服务时,我收到一个错误,好像没有空的构造函数。 我怎样才能保持这些服务和实现 类 不变,并让我的 WCF 服务与这些构造函数一起工作。

WCF 本身要求 服务宿主有一个default/no-argument 构造函数;标准的 WCF 服务创建实现没有花哨的激活——而且它肯定 不会 处理依赖注入! - 创建服务主机对象时。

要绕过此默认要求,请使用 WCF Service Host Factory (such as one provided with Castle Windsor WCF Integration) 创建服务并使用适当的构造函数注入依赖项。其他 IoC 提供了自己的集成工厂。在这种情况下,IoC 感知服务工厂创建服务并连接依赖项。

要在没有 IoC(或以其他方式处理服务工厂)的情况下使用 DI ,请创建一个无参数构造函数,该构造函数调用具有所需依赖项的构造函数,例如

public class SalesService : Service<Sales>, ISalesService
{
   private readonly IRepositoryAsync<Sales> _repository;

   // This is the constructor WCF's default factory calls
   public SalesService() : this(new ..)
   {
   }

   protected SalesService(IRepositoryAsync<Sales> repository)
   {
      _repository = repository;
   }
}