2

I have a standard .net ApiController with the following code:

public class LibraryApiController : ApiController
{
    private readonly ILibraryAssetRepository _repository;

    public LibraryApiController() : this(new LibraryAssetRepository())
    {

    }

    public LibraryApiController(ILibraryAssetRepository repository)
    {
        if(repository == null) throw new ArgumentNullException(nameof(repository));

        _repository = repository;
    }
}

I would like to get rid of the parameterless constructor, but then I run into the dreaded:

An error occurred when trying to create a controller of type 'ApiController'. Make sure that the controller has a parameterless public constructor.

I am using Sitecore's builtin dependency injection (Microsoft.DependencyInjection)

I have only found examples using SitecoreApiControllers. How do I solve this using an ApiController?

  • Can you the Sitecore ServicesController ? it inherits from ApiController – Abhay Dhar Jan 29 at 8:57
  • letsdositecore.wordpress.com/2018/11/13/… there is an example for ApiControllers as well – Abhay Dhar Jan 29 at 9:00
  • @AbhayDhar If you add a commen/answer about the part where an ApiController is registered and write an example: serviceCollection.AddTransient(typeof(GenericCalloutApiController)); I will mark that answer as accepted solution. Thanks! – Hos Jan 29 at 18:28
2

As described in this blog post -https://letsdositecore.wordpress.com/2018/11/13/possibly-simplest-way-of-enabling-dependency-injection-in-sitecore-controllers-and-apicontrollers/ , you can use a ServiceConfigurator to register your API controllers using Sitecore DI. Don't forget to patch it in.

namespace Feature.GenericCallout
{
    public class GenericCalloutServicesConfigurator : IServicesConfigurator
    {
        public void Configure(IServiceCollection serviceCollection)
        {
            serviceCollection.AddTransient(typeof(GenericCalloutController));
            serviceCollection.AddTransient(typeof(GenericCalloutApiController));
        }
    }
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.