Implicit dependencies and ‘copy local’ fails to copy

A common scenario with .NET Solutions is that you have a Project, lets call it Project X, that have dependencies to a library without explicitly using it from code. You have a host project typically a Web or Windows client Project that uses Project X, even with copy local set Visual Studio will fail to load that implicit dependency and you will receive a Runtime error when trying to run the project.

One solution is to add this reference to the host project even if it does not have any direct dependency to the library. I think this is bad practice and will get very hard to maintain in a large project with lots of dependencies and assemblies.

A better solution that I use is to create a little helper method

static RepositoryBase() {
   Util.EnsureStaticReference<System.Data.Entity.SqlServer.SqlProviderServices>();
}

It should be called as close to the dependency as possible for readability. In above example I have a Repository base class which uses Entity framework. I call it from the static constructor.

The implementation of EnsureStaticReference looks like this

    public static class Util
    {
        public static void EnsureStaticReference<T>()
        {
            var dummy = typeof(T);
            if(dummy == null)
                throw new Exception("This code is used to ensure that the compiler will include assembly");
        }
    }
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