简体   繁体   中英

How to let CLR know which assembly to pick from GAC?

using System;
using System.Collections.Generic;
using System.Text;
using Shapes;

namespace ShapeUser
{
    public class ShapeUser
    {
        public static void Main() 
        {
            Circle c = new Circle(1.0F);
            Console.WriteLine("Area of Circle(1.0) is {0}", c.Area());
            Console.ReadKey(); // press a key to exit program
        }
    }
}

This program is using Shapes assembly which is in the GAC. If there is only one assembly, its fine. But, the GAC may contain other assemblies with the same name (but different version and key).

So, how to tell the CLR to load my assembly only not the others having same name?

I'm confused. I know it is protected by public key encryption but still we should be having some private key in the program from where we are accessing it. Please clear my confusion.

When you reference an assembly in the GAC you must reference it by its strong name , a combination of its name, version number, culture (if provided) plus a public key and digital signature (assemblies must be signed to be considered strongly named, and only strongly named assemblies may be added to the GAC).

If you reference a strongly named assembly then you are already uniquely identifying what assembly you wish to use. If you are referencing an assembly that isn't strongly named then that assembly can't be loaded into the GAC (and the .Net runtime won't check there anyway, see How the Runtime Locates Assemblies ).

If you are referencing a strongly named assembly (or in fact any assembly) and want to accept multiple different versions of that assembly (eg v1.0.0.0 and v1.0.1.0), or you want to release a newer version of your assembly and allow existing applications to continue functioning without needing to be recompiled then you can use Assembly Binding Redirection .

If you want to be able to reference an assembly regardless of what key is used to sign that assembly then you are best off not signing that assembly at all (and therefore not adding it to the GAC).

I believe that you can also subscribe to the assembly resolve event , however using assembly binding redirection is the preferred method, as long as it provides the desired behaviour.

When you compile, you can specify the exact version to use. That's the version that will be loaded at execution time. If you're using Visual Studio, the Properties for the reference will contain the version number, as well as a flag to say whether the exact version number has to be loaded or not.

The assembly is defined by its name, public key token, and version. When you create a reference, you can be specific and indicate each of these values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM