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?

3
  • Can you the Sitecore ServicesController ? it inherits from ApiController
    – Abhay Dhar
    Jan 29, 2020 at 8:57
  • letsdositecore.wordpress.com/2018/11/13/… there is an example for ApiControllers as well
    – Abhay Dhar
    Jan 29, 2020 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, 2020 at 18:28

1 Answer 1

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));
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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