0

I have a dll that other applications use. It relies on a 3rd party dll that updates fairly regularly. As long as the version I need or greater is present then I am happy.

But Visual Studio forces the exact version I need on the apps that use my dll.

I want to add an event handler to AppDomain.CurrentDomain.AssemblyResolve so I can check for a later version and just use that. But I don't know where to add it.

Most apps would put this in program.cs startup. But a dll does not have that.

I would put it in a static constructor, but I have many classes that use this 3rd party dll. It seems messy to put this event attach into each class.

Is there any other option?

jcopenha
  • 3,935
  • 1
  • 17
  • 15
Vaccano
  • 78,325
  • 149
  • 468
  • 850

2 Answers2

1

Ben Hall has an example of doing this http://blog.benhall.me.uk/2006/08/appdomaincurrentdomainassemblyresolve.html:

private Assembly AssemblyResolveHandler(object sender,ResolveEventArgs e)
{
    try
    {
        string[] assemblyDetail = e.Name.Split(',');
        string assemblyBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        Assembly assembly = Assembly.LoadFrom(assemblyBasePath + @"\" + assemblyDetail[0] + ".dll");
        return assembly;
    }
    catch (Exception ex)
    {
        throw new ApplicationException("Failed resolving assembly", ex);
    }
}

Make sure the assignment of the delegate to AssemblyResolve is done before you try to resolve the types you want to "redirect". http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx shows and example of this.

Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
  • Yes, but where do I attach to this? A dll has no OnLoad method to let me get this attached before the failure happens. (That is the point of the question.) – Vaccano Aug 24 '12 at 17:52
  • In terms of a dll, that dll would have to be loaded *before* the types you want to redirect are loaded. Without doing *that* in Main(), there's no way to guarantee that. At which point, you're basically forced to do the event subscription in main. – Peter Ritchie Aug 24 '12 at 18:10
1

Can you use assembly binding redirect?

<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Foo.Bar" publicKeyToken="***" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.1"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>
oleksii
  • 35,458
  • 16
  • 93
  • 163
  • This is the best solution. I don't like it because it forces the apps that use my dll to deal with the fact that I don't have the same version as they do (I would like my code to not cause any headaches for those who forget to do this). – Vaccano Aug 24 '12 at 17:53