Unity registration fails after iisreset

2019-07-19 13:09发布

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?

1条回答
smile是对你的礼貌
2楼-- · 2019-07-19 13:47

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 the AllClasses.FromAssemblies helper method.

.RegisterTypes(
    AllClasses.FromAssemblies(
             BuildManager.GetReferencedAssemblies().Cast<Assembly>()),
    WithMappings.FromMatchingInterface,
    WithName.Default,
    overwriteExistingMappings: true);   

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:

.RegisterTypes(
    AllClasses.FromAssemblies(typeof(Foo).Assembly),
    WithMappings.FromMatchingInterface,
    WithName.Default,
    overwriteExistingMappings: true);
查看更多
登录 后发表回答