I am wondering if there is a way to create a class library that contains web API, so I can use the dll as a plug-in, to inject into the MVC application.
Thank you in advance for your help.
I am wondering if there is a way to create a class library that contains web API, so I can use the dll as a plug-in, to inject into the MVC application.
Thank you in advance for your help.
Web API methods are called over HTTP, so calling a Web API service requires it to be hosted somewhere and called using a suitable client as detailed in @David's link. You can self-host Web API, so in theory you could have an assembly local to an MVC application which contained a class which set up and then called a self-hosted Web API service.
You would inject the Web API service behind an interface, something like this:
public interface IProductsService
{
IEnumerable<Product> GetAllProducts();
}
...implemented something like this:
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.
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