public abstract class ServiceAgentBase<TService>
{
private readonly IServiceClientFactory _factory;
protected ServiceAgentBase(IServiceClientFactory factory)
{
Guard.ArgumentNotNull(factory, "factory");
_factory = factory;
}
protected void Work(Action<TService> work)
{
Guard.ArgumentNotNull(work, "work");
Work<object>(service =>
{
work(service);
return null;
});
}
protected TResult Work<TResult>(Func<TService, TResult> work)
{
Guard.ArgumentNotNull(work, "work");
var client = _factory.Create<TService>();
var communicationObject = client as ICommunicationObject;
return communicationObject != null ? communicationObject.Using(c => work((TService)c)) : work(client);
}
}
首先有如上的base类,
接着在我们定义子类时:
public class SalesCompanyPsiHandlingServiceAgent : ServiceAgentBase<ISalesCompanyPsiHandlingService>,
ISalesCompanyPsiHandlingService
{
public SalesCompanyPsiHandlingServiceAgent(IServiceClientFactory factory)
: base(factory)
{
}
// ARCH: サービスインターフェースの各メソッドの実装では、基底クラスの Work メソッドを呼び出し、
// そこに渡すデリゲートの中で受け取ったサービスインターフェースのインスタンスに処理を移譲する。
public SalesCompanyPsiDto[] Find(ModelSearchConditionDto condition)
{
return Work(service => service.Find(condition));
}
public void Store(SalesCompanyPsiDto[] salesCompanyPsisToCreate, SalesCompanyPsiDto[] salesCompanyPsisToUpdate)
{
Work(service => service.Store(salesCompanyPsisToCreate, salesCompanyPsisToUpdate));
}
}
在Find方法中,我们直接返回work,因为TService已经赋值,所以我们用service来代表TService,
通过lamda表达式,就能将IServicexxx的接口类型参数转换为DTO类型参数并整个实现。