我使用的是.NET 4.5,C#.NET,WCF存储库模式
WCF服务
<@ ServiceHost Language="C#" Service="CustomerService" @>
<@ ServiceHost Language="C#" Service="OrderService" @>
<@ ServiceHost Language="C#" Service="SalesService" @>
<@ 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服务与这些构造函数一起工作。
答案 0 :(得分:2)
WCF本身要求服务主机具有默认/无参数构造函数;标准的WCF服务创建实现没有花哨的激活 - 而且它肯定不处理依赖注入! - 创建服务主机对象时。
要绕过此默认要求,请使用WCF Service Host Factory(例如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;
}
}