I have add a web api project in "Presentation" directory. I want to use nopCommerce servcies directly.
Can anyone provide me an example of how to use dependency injection (autofac) to inject NopCommerce service interface into Web Api Controller constructor?
I have add codes to Global.asax,
public class WebApiApplication : System.Web.HttpApplication
{
void ConfigureApi()
{
var config = GlobalConfiguration.Configuration;
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(typeof(CustomerService)
.Assembly).Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces().InstancePerApiRequest();
var container = builder.Build();
// Set the dependency resolver implementation.
var resolver = new AutofacWebApiDependencyResolver(container);
config.DependencyResolver = resolver;
}
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
ConfigureApi();
}
}
And CustomerController, I add codes:
public CustomerController(ICustomerService customerService)
{
this._customerService = customerService;
}
but I got an error like this:
<Message>An error has occurred.</Message><ExceptionMessage>An error occurred when trying to create a controller of type 'CustomerController'. Make sure that the controller has a parameterless public constructor.</ExceptionMessage><ExceptionType>System.InvalidOperationException</ExceptionType><StackTrace> 在 System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
在 System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
在 System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()</StackTrace>
Thank you.