I am writing web api using Dependency injection, Unit of work using repositories and Autofac as a container. The addiction was quickly introduced 24 hours ago, but suddenly, when I started working today, I kept getting an error
"Message": "An error occurred.", "ExceptionMessage": "An error occurred while trying to create a controller of type 'SearchController. Make sure the controller has no public constructor.", "ExceptionType": "System.InvalidOperationException",
I will include my signatures and how I register types, and will be very happy if someone can indicate what might be wrong with my code.
On my api web controller i have
private IUnitOfWork<Listing> _unitOfWork = null; public SearchController(IUnitOfWork<Listing> unitOfWork) { _unitOfWork = unitOfWork; }
The unit of work accepts a generic type parameter to create the repository.
In my WebApiConfig.cs, I register the types below
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)); builder.RegisterGeneric(typeof(UnitOfWork<>)).As(typeof(IUnitOfWork<>)).InstancePerDependency(); builder.RegisterType(typeof(SearchController)).UsingConstructor(typeof(IUnitOfWork<Listing>));
I am registering a SearchController to use a constructor that accepts IUnitOfWork <>. All of this worked well before I added the Mocked unit tests, but for some purposes I keep getting this error. I also registered DependencyResolver
var container = builder.Build(); var resolver = new AutofacWebApiDependencyResolver(container); config.DependencyResolver = resolver;
c # dependency-injection unit-of-work autofac asp.net-web-api2
Ali Baig
source share