1

I have a .NET dll wrapper around a mixed (Managed/Unmanaged) type. If some crucial dll's are missing from the hard drive or their location is not entered into the path, then the type will not load resulting in a TypeLoadException("Could not load file or assembly or one of its dependencies"). This hampers xcopy deployability of any utility that consumes this class library.

I would prefer to fix this problem without instructing all clients to change client code. I hope to achieve this by running code before the type is loaded by the CLR. I have included its dependencies in a zip file which is included with the distribution.

Clients call into a static factory method.

var MyMixedTypeInstance = MyMixedType.Create();

However, since the factory method signature return type is MyMixedType, then MyMixedType is attempted loaded before any code inside the create method is executed. I have considered make the return type an interface to avoid this. But if the interface at some deals with (eg returns) a concrete mixed type, then AFAICT I'm back to square one.

I attempted stuff like using a static constructor, but it seems (as maybe all of you others know) that types exposed by the public API are immediately loaded. However, I do not know much about how the loading of types unfold, so I may be missing something obvious. I know that you can help the CLR resolve assemblies, but I do not know if this relates to a type.

Naturally, it would be possible to create a complete separate "MakeSureNeededBinariesAreInPlaceAndInPath" kind of method and demand/force all clients to invoke it prior to calling the Create() method, but I would like to avoid it if I can.

Is there for instance any attribute I can decorate the type with to intercept the type loading of the class?

Tormod
  • 4,551
  • 2
  • 28
  • 50
  • 1
    Not sure that it's what you need, but you can try to listen the event AssemblyResolve of the class AppDomain. – schglurps Apr 02 '14 at 17:18
  • 1
    This might help http://stackoverflow.com/questions/1803540/load-assembly-at-runtime-and-create-class-instance/16744357#16744357 – reggaeguitar Apr 02 '14 at 17:47
  • The assembly resolves just fine. However, when the exact type is consumed (or a class that exposes it), it throws the exception as described. I don't think TypeResolveEvent is what I'm looking for as that is about locating the proper assembly. And even if it was, it would be up to the client to hook up the handler. I need to run custom code when somebody tries to access types in my library before the type class gets initialized. – Tormod Apr 02 '14 at 18:18

0 Answers0