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

C# 具有参数化构造函数的WCF服务,c#,.net,wcf,C#,.net,Wcf,我正在使用.NET4.5、C#.NET、WCF存储库模式 WCF服务 Customer.svc: Order.svc: Sales.svc: Products.svc: 实现类 public class CustomerService : Service<Customer>, ICustomerService.cs { private readonly IRepositoryAsync<Customer> _repository; public Custo

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

WCF服务

  • Customer.svc:
  • Order.svc:
  • Sales.svc:
  • Products.svc:
实现类

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;
   }
}
公共类CustomerService:Service,icCustomerService.cs
{
专用只读IRepositoryAsync存储库;
公共CustomerService(IRepositoryAsync存储库)
{
_存储库=存储库;
}
}
公共类OrdersService:Service,IOrdersService.cs
{
专用只读IRepositoryAsync存储库;
公共订单服务(IRepositoryAsync存储库)
{
_存储库=存储库;
}
}
公共类SalesService:Service,ISalesService.cs
{
专用只读IRepositoryAsync存储库;
公共销售服务(IRepositoryAsync存储库)
{
_存储库=存储库;
}
}
当我运行我的WCF服务时,我得到一个错误,就像没有空的构造函数一样。 如何保持这些服务和实现类不变,并使我的WCF服务与这些构造函数一起工作。

WCF本身要求服务主机具有默认/无参数构造函数;标准的WCF服务创建实现没有奇特的激活——而且它肯定不会处理依赖注入创建服务主机对象时

要绕过此默认要求,请使用(如随附的)创建服务并使用适当的构造函数注入依赖项。其他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;
   }
}
公共类SalesService:Service,ISalesService
{
专用只读IRepositoryAsync存储库;
//这是构造函数WCF的默认工厂调用
public SalesService():此(新..)
{
}
受保护的SalesService(IRepositoryAsync存储库)
{
_存储库=存储库;
}
}

关键字:
ServiceHostFactory
,例如,请参阅,我建议使用DI容器,而不是手动构造依赖项,例如请参阅。@abatishchev我也是:但是“哪一个”可以是蠕虫和单独的主题。然而,这种没有IoC的DI是一种选择。我使用了温莎城堡WCF设施,它工作得非常好。你绝对应该试一试!因为我正在从事POC项目,所以现在我使用空构造函数,但最终我更喜欢使用Unity应用程序块进行依赖项注入