如何将依赖项注入asmx webservice webmethod?

iAt*_*_it 1 c# asmx

我有这个方法的asmx webserice

[WebMethod]
double GetBookPrice(int bookID)
{
    //instantiates a DiscountService,DeliveryService and a couple of other services

    //uses various methods of these services to calculate the price
    //e.g. DiscountService.CalculateDiscount(book)

}
Run Code Online (Sandbox Code Playgroud)

有4种服务是此方法的依赖项.

现在如何测试这种方法?我需要注入这些依赖项?或者我应该这样做?客户端只是发送一个int来检查价格.

谢谢

Dan*_*ann 5

如果所有GetBookPrice方法都在进行并将其int传递给另一个方法,然后返回这些结果,我会说测试服务方法具有可疑的价值.测试它并没有什么坏处,如果你想扩展GetBookPrice方法中的功能,它可能有价值.

但是,一般来说,如果你想测试你的服务,你可以通过构造函数注入和构造函数链接来执行标准IOC:

public class FooWebService
{
    private readonly ISomeDependency dependency;
    public FooWebService(ISomeDependency dependency)
    {
        //this is what you call during your testing
        this.dependency = dependency;
    }
    public FooWebService() : this(new ConcreteDependencyImplementation())
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

在进行测试时,您会传入依赖项(或依赖项!)的实例.当您不进行测试时,将通过调用无参数构造函数自动创建和提供依赖项.