我有一个像这样的Web服务门户:
interface MyWebServices
{
ReportsService.Conversion[] Conversions();
ExportService.Advertiser[] ExportAdvertisers();
}
public class MyWebServices : IMyWebServices
{
private string apiKey;
public CakeWebService(string apiKey)
{
this.apiKey = apiKey;
}
public ExportService.Advertiser[] ExportAdvertisers()
{
var service = new ExportService.export();
int advertiserID = 0;
var advertisers = service.Advertisers(this.apiKey, advertiserID);
return advertisers;
}
public ReportsService.Conversion[] Conversions()
{
var target = new ReportsService.reports();
DateTime from = new DateTime(2012, 1, 1);
DateTime to = DateTime.Now.AddDays(1);
int affiliateID = 0;
int offerID = 0;
var conversions = target.ConversionExport(this.apiKey, from, to, affiliateID, offerID, false);
return conversions;
}
}
每个方法都会创建一个Web服务实例,然后在调用之前对其进行配置。
我宁愿让我的UnityContainer做这个配置,但是我还想要“按需方法注入”......
我认为这可能是使用拦截扩展的一个很好的候选者,但我无法知道这是否真的有效 - 这是一种合理的方式吗?
答案 0 :(得分:0)
解决方案对我来说看起来很简单,为什么不创建IReportService
和IExportService
并让uni将具体实现注入到服务中,然后稍微重构一下这些类:
public interface IExportService
{
ExportService.Advertiser[] ExportAdvertisers();
}
public class ConcreteExportService : IExportService
{
public ExportService.Advertiser[] ExportAdvertisers()
{
var service = new ExportService.export();
int advertiserID = 0;
var advertisers = service.Advertisers(this.apiKey, advertiserID);
return advertisers;
}
}
public interface IReportService
{
ReportsService.Conversion[] Conversions();
}
public class ConcreteReportService : IReportService
{
public ReportsService.Conversion[] Conversions()
{
var target = new ReportsService.reports();
DateTime from = new DateTime(2012, 1, 1);
DateTime to = DateTime.Now.AddDays(1);
int affiliateID = 0;
int offerID = 0;
var conversions = target.ConversionExport(this.apiKey, from, to, affiliateID, offerID, false);
return conversions;
}
}
public class MyWebServices : IMyWebServices
{
private string apiKey;
private IExportService _exportService;
private IReportService _reportService;
public MyWebServices(
IExportService exportService,
IReportService reportService)
{
this._exportService = exportService;
this._reportService = reportService;
}
public ExportService.Advertiser[] ExportAdvertisers()
{
return this._exportService.ExportAdvertisers();
}
public ReportsService.Conversion[] Conversions()
{
return this._reportService.Conversions();
}
public CakeWebService(string apiKey)
{
this.apiKey = apiKey;
}
}