Unity registration fails after iisreset

吃可爱长大的小学妹 提交于 2019-12-11 02:42:12

问题


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:


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


来源:https://stackoverflow.com/questions/30264897/unity-registration-fails-after-iisreset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!