2

I have a method in class library that scans all loaded assemblies for types that implement a certain interface a la Getting all types that implement an interface.

var type = typeof(IMyInteraface);
var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

When installing the class library into projects, I occasionally run into a FileNotFoundException like:

Could not load file or assembly 'AAA.BBB.CCC, Version=1.2.3.4, Culture=neutral, PublicKeyToken=abcdef0123456789a' or one of its dependencies. The system cannot find the file specified.

I want to rewrite the LINQ query into something more safe from errors. For my purposes, if an assembly cant be loaded, then I don't have to worry about trying to load any type that belongs to it. How is this done?

Community
  • 1
  • 1
Jeff
  • 13,943
  • 11
  • 55
  • 103
  • 1
    The first thing to do would be to narrow down exactly where the exception is occurring. Is it occurring in the call to AppDomain.CurrentDomain.GetAssemblies()? In the ToList()? In the SelectMany()? in the Where()? – Nathan Oct 17 '11 at 16:40
  • Any reason to stick with linq? Why not use a foreach to loop through the assemblies and try/catch any (load) error? – Eddy Oct 17 '11 at 16:52
  • @Eddy No, I don't need to stick with LINQ. – Jeff Oct 17 '11 at 17:08
  • @Nathan I am only receiving these errors on production environments. I cannot reproduce them anywhere else and I have been unable to manufacture the error on my own. That is why I came here. – Jeff Oct 17 '11 at 17:10
  • @Jeff - you can get stack traces no? – Nathan Oct 17 '11 at 19:26

1 Answers1

2

You can always decompose the LINQ into nested foreach loops and add lots of try-catch blocks, and ignore any assembly and any type that gives you an error.

var interfaceType = typeof(IMyInterface);
var types = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) {
    try {
        foreach (var type in assembly.GetTypes()) {
            try {
                if (interfaceType.IsAssignableFrom(type))
                    types.Add(type);
            } catch (FileNotFoundException) {}
        }
    } catch (FileNotFoundException) {}
}
Joe White
  • 94,807
  • 60
  • 220
  • 330
  • The `try-catch` needed to be around the `Assmebly.GetTypes` call. Thanks for the direction! – Jeff Oct 18 '11 at 13:26