Unity 3 Configuration By Convention not finding Types in Web Project

人走茶凉 提交于 2019-12-21 18:06:22

问题


I am trying to get this convention configuration working but I am having a problem in my ASP.NET MVC5 Project..

I have added the following in my Application_Start method and hooked it up to DependencyResolver

 public static IUnityContainer CreateContainer()
    {
        IUnityContainer container = new UnityContainer();

        container.RegisterTypes(

            AllClasses.FromAssembliesInBasePath(),

            WithMappings.FromAllInterfaces,

            WithName.Default,

            WithLifetime.ContainerControlled);

        return container;
    }

But it fails to register any types, on closer inspection, when I see whats in AllClasses.FromAssembliesInBasePath() it always runs null or empty.

Am I doing something wrong? is there a better place I should put this?

Thanks. Ste.


回答1:


The reason might be that the domain base path is not what you thought.

Please try this see if it registers anything:

  container.RegisterTypes(

        AllClasses.FromAssemblies(Assembly.GetExecutingAssembly()),

        WithMappings.FromAllInterfaces,

        WithName.Default,

        WithLifetime.ContainerControlled);



回答2:


I guess the suggestion above to use AllClasses.FromAssemblies(Assembly.GetExecutingAssembly()) will work only when you have the WebAPI as the only project, if your business logic and data access are present in different assemblies it might not work as expected.

I faced the same issue with AllClasses.FromAssembliesInBasePath() method in Unity.

Please refer to the code present in the following location:

Unity Framework Project :Unity.RegistrationByConvention

File: AllClasses.Desktop.cs

Method: GetAssembliesInBasePath

Line: 59

basePath = AppDomain.CurrentDomain.BaseDirectory;

This set the value of basePath to the root of the project \WebAPIProject\ instead of pointing to the bin folder.

If we set basePath as shown below it will return the path appropriately.

basePath = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;

I am not sure if this requires a fix in Unity Framework, having said that, to get things working as expected, the relative search path was handy in my case.

I abstracted code from Unity to rewrite the AllClasses class with the fix mentioned above.



来源:https://stackoverflow.com/questions/22830345/unity-3-configuration-by-convention-not-finding-types-in-web-project

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