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

本文关键字:WCF 服务 构造函数 参数 | 更新日期: 2023-09-27 18:02:34

我使用的是。net 4.5, c#。. NET、WCF库模式

WCF服务

  • 客户。svc: <@ ServiceHost Language="C#" Service="CustomerService" @>
  • 订单。svc: <@ ServiceHost Language="C#" Service="OrderService" @>
  • 销售。svc: <@ ServiceHost Language="C#" Service="SalesService" @>
  • 产品。svc: <@ ServiceHost Language="C#" Service="ProductsService" @>
实现类

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服务

WCF本身要求 Service Host有一个默认的/无参数的构造函数;标准的WCF服务创建实现没有花哨的激活——而且它肯定没有处理依赖注入!-创建Service Host对象时。

要绕过这个默认需求,请使用WCF服务主机工厂(例如Castle Windsor WCF Integration提供的工厂)来创建服务并使用适当的构造函数注入依赖项。其他ioc提供了自己的集成工厂。在本例中,支持ioc的服务工厂创建服务并连接依赖项。

要使用DI 而不使用 IoC(或以其他方式处理Service Factory),请创建一个无参数构造函数,该构造函数调用具有所需依赖项的构造函数,例如
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;
   }
}