Problems loading assemblies using UnityContainer.RegisterTypes. My app is running on IIS7

May 14, 2014 at 6:46 PM
Edited May 14, 2014 at 6:50 PM

I have a problem trying to load assemblies with necesary classes using Unity. My web application is MVC5 and it is running on IIS7.

Here my code (The idea is make the unity registrations automatically and not one by one. How you will see the main project webApp have not references with the dataaccess classes):
These are the assemblies dependencies:
  • WebApp.dll (Make reference to BusinessLogic)
  • BusinessLogic.dll (Make reference to DataAccessInterfaces)
  • DataAccessInterfaces.dll (Not have dependencies)
  • SqlServerDataAccess.dll (Make reference to DataAccessInterfaces)
Then...When I ran my application one time then all is Ok. Container will register all necesary Interfaces and clasess. But when I restart the server and try run my application again then the container have not registered my classes and have registered just { Microsoft.Practices.Unity.IUnityContainer }. Then when I try resolve some type then an Unity exception is thrown.

What is the problem??? the way how I'm loading assemblies??...maybe the IIS7 configuration???...
May 15, 2014 at 2:09 PM
It sounds like you are seeing the same situation as this: . And was discussed in this thread.

You can change to use AllClasses.FromAssembliesInBasePath() instead of relying on assemblies that are already loaded.

Randy Levy
Enterprise Library support engineer
Support How-to
May 15, 2014 at 3:01 PM
I have solved the problem. :)

The way "AllClasses.FromLoadedAssemblies" of unity just works when the application is on debug mode on IIS7 Express. If the solution is
deployed on local or remote IIS7. The first time it will works fine, but the next times it will fails. Because the II7 will create a temporary folder and inside it another folder per each assembly. Then the method container.RegisterTypes(AllClasses.FromLoadedAssemblies,.....) will read in the temporary folder that contains just Xpo.CapacityTool.WebApp assembly and will not load the specific dataAccess assemblies because they are not there. The solution was load the assemblies manually from the [domain path]/bin folder. Here the code:
public static void Register(UnityContainer container)
    var assemblies = GetDataAccessAssemblies();

private static IEnumerable<Assembly> GetDataAccessAssemblies()
    var assemblyPattern = @".([A-Za-z0-9\-]+)DataAccess";
    var binPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
    var myAssemblies = Directory.GetFiles(binPath, "*.dll", SearchOption.TopDirectoryOnly).Where(name => Regex.IsMatch(name, assemblyPattern));
    return myAssemblies.Select(dll => Assembly.Load(Assembly.LoadFile(dll).FullName)).ToList();
Marked as answer by foxhard on 5/15/2014 at 7:01 AM