Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the right way to register types in Unity using a convention-based approach?

I am registering my types by convention, but some types from my other assemblies are not registering consistently. Sometimes they are registered, while other times they aren't. It's not consistently failing. Here's some trace data:

...is an interface and cannot be constructed. Are you missing a type mapping?

I want to eliminate 3rd party dlls and such from my registration process. Is this the right way to do this?

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        container.RegisterTypes(
         AllClasses.FromLoadedAssemblies().Where(t => t.Namespace != null && t.Namespace.StartsWith("MY NAMESPACEs ONLY")),
         WithMappings.FromMatchingInterface,
         WithName.Default);

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}

EDIT: This also randomly happens when I remove the "Where" filter. I've used this registration methodology before and this NEVER happened. What's going on?

like image 751
Big Daddy Avatar asked Nov 09 '22 07:11

Big Daddy


1 Answers

I stumpled upon this myself and realised that it was AllClasses.FromLoadedAssemblies() that didn't work as expected (It probably worked as intended, just not how I expected it). It seemed as it was loading the assemblies in a different order in different environments. I wasn't able to figure out the solution for this, but I found a workaround.

The solution in my case was to avoid AllClasses.FromLoadedAssemblies() by using BuildManager.GetReferencedAssemblies().

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

See the original question that solved it in my case here: Unity registration fails after iisreset

like image 132
smoksnes Avatar answered Nov 14 '22 21:11

smoksnes