2

我想知道是否有一种方法可以创建一个包含 Web API 的类库,这样我就可以使用 dll 作为插件来注入 MVC 应用程序。

预先感谢您的帮助。

4

2 回答 2

1

Web API 方法通过 HTTP 调用,因此调用 Web API 服务需要将其托管在某处并使用合适的客户端调用,如@David 的链接中所述。您可以 自托管 Web API,因此理论上您可以在 MVC 应用程序本地有一个程序集,其中包含一个类,该类设置然后调用自托管 Web API 服务。

您将在接口后面注入 Web API 服务,如下所示:

public interface IProductsService
{
    IEnumerable<Product> GetAllProducts();
}

...实现了这样的事情:

public class SelfHostedWebApiProductsService
{
    public SelfHostedWebApiProductsService()
    {
        // Set up a self-hosted Web API service
    }

    public IEnumerable<Product> GetAllProducts()
    {
        // Call your self-hosted WebApi to get the products
    }
}

Configure your DI container to use SelfHostedWebApiProductsService for the IProductsService interface, and away you go. This article details how to set up and call a self-hosted Web API.

As the SelfHostedWebApiProductsService sets up the self-hosted Web API in its constructor - a relatively expensive operation - you might want to consider giving this class a singleton lifetime in your DI container.

于 2013-03-29T12:18:19.527 回答
0

You could Self-Host a Web API: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api

You can put all your controllers in a Class Library project.

Then use Autofac to resolve the dependencies in your host project: https://code.google.com/p/autofac/wiki/WebApiIntegration

于 2013-04-03T02:11:58.620 回答