I am registering a load of dependencies like so.
container.RegisterTypes(AllClasses.FromLoadedAssemblies(),
WithMappings.FromMatchingInterface,
WithName.Default,
overwriteExistingMappings: true);
This registers things fine and the web api endpoints are properly configured.
If I do iisreset
or simply wait for a bit then things fail with
The error message is not terribly helpful
"exceptionMessage": "An error occurred when trying to create a controller of type 'ApiController'. Make sure that the controller has a parameterless public constructor.",
Which of course the controller does not, and should not, have.
I am not sure what is going on... but if I register the dependencies explicitly
container.RegisterType<IDoAThing, Domain.Things.DoAThing>(new HierarchicalLifetimeManager());
Then it all works.
How can I get the 'by convention' registration to keep working?
Looks like after the
iisreset
, the assemblies have not been loaded yet into the app domain by the time your Unity registration kicks in.Since you are using the helper method
AllClasses.FromLoadedAssemblies()
, it will not register classes in assemblies that were not yet loaded.Try getting the referenced assemblies with
BuildManager.GetReferencedAssemblies
, which will obtain a list of assemblies in the bin folder. Then perform your Unity registrations using those assemblies and theAllClasses.FromAssemblies
helper method.In the worst case you could use a well-known class from each of your assemblies, getting its assembly via reflection and use it for your registration as in this simplified sample: