Handling Duplicate Libraries with MEF

While building the composition/DI piece for the Commons Library, one problem I ran into was the fact that if you told MEF to load assemblies from a number of different places – and they all had copies of the same library (which is possible especially with common dependencies), MEF would load the exports in each assembly as many times as it finds it. What you end up with then is a whole bunch of matching exports for a contract that you expect only one of.

One easy way to handle this is to assume that FullName for an assembly truly uniquely identifies it (i.e. the code within two instances of an assembly with the same FullName should not be different). We can then do something like the following (assume here that modulesDirectories is anIEnumerable<string> that consists of the list of directories we want to load our assemblies from).

In the above snippet, we use a class AssemblyEqualityComparer, which can be defined as follows:

You can find the full Commons Library code implementation for this here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s