1
votes

I have written the following piece of code and I'm looking to refine it. using Unity DI, I need to register concrete classes along with the interfaces they implement. The advantage of the method is to remove the need to keep registering new classes when added.

I have reduced the code to


    IUnityContainer container = new UnityContainer();
            // from
            // Factories
            // container.RegisterType();

            // Services
            // container.RegisterType();
            // container.RegisterType();
            //......
            // to

    var assemblies = AppDomain.CurrentDomain.GetAssemblies()
        .Where(x => x.GetName().Name.Contains("Romabravo.ApplicationManager"));

    foreach (var assembly in assemblies)
    {
        var types = assembly.GetExportedTypes();
        foreach (Type t in types)
        {
            var interfaces = t.GetInterfaces().Where(x => x.FullName != null &&
            x.FullName.Contains("Romabravo.ApplicationManager")).ToList();

                foreach (var item in interfaces)
                {
                    var interfaceImplementers = AppDomain.CurrentDomain.GetAssemblies()
                    .SelectMany(s => s.GetTypes())
                    .Where(p => item.GetTypeInfo().IsAssignableFrom(p) && 
                    item.FullName.Contains("Romabravo.ApplicationManager"))
                    .Select(x => x).Where(x => !x.IsInterface && !x.IsAbstract).ToList();

                    if (interfaceImplementers != null)
                    {
                        foreach (var implementer in interfaceImplementers)
                        {
                            container.RegisterType(item, implementer);
                        }
                    }
                }
            }
        }

    return container;


Just looking for a way to optimise it further.

1
Randy's answer seems pretty good but I would like to comment on the overall approach. If you do this sort of thing, it will save you maybe 5 minutes out of your day to register the new class. Now imagine any developer maintaining your code two years from now, trying to figure out where a dependency is coming from. You are probably adding more than 5 minutes to his day, especially if he is reconstructing a past changeset to debug a problem, because he'll have to figure out which class ended up registered. Personally I would lean toward making the dependency explicit in code.John Wu

1 Answers

2
votes

If you are using Unity 3 then you can use registration by convention which could simplify the code a bit:

container.RegisterTypes(
    AllClasses.FromLoadedAssemblies()
      .Where(a => a.FullName.Contains("Romabravo.ApplicationManager")),
    WithMappings.FromMatchingInterface);