0

我有一个这样的 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 做这个配置,但我想要像“按需方法注入”这样的东西......

我认为这可能是使用拦截扩展的好选择,但我无法知道这是否真的是一个可行的方案 - 这是一个合理的方法吗?

4

1 回答 1

0

解决方案对我来说看起来很简单,为什么不创建IReportServiceIExportService让统一将具体实现注入服务,然后稍微重构您的类,使其看起来像这样:

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;
    }      
}
于 2012-04-25T13:16:29.630 回答