aambrozkiewicz
aambrozkiewicz

Reputation: 552

Deserialization of externally loaded assembly types

I load external libraries using

Assembly assembly = Assembly.LoadFile(assemblyPath);

foreach (Type assemblyType in assembly.GetTypes())
{
    if (assemblyType.IsSubclassOf(typeof(Chip.Chip)))
    {
        Chip.Chip chip = (Chip.Chip)Activator.CreateInstance(assemblyType);
        this[chip.Name] = new ChipAssembly()
        {
            Name = chip.Name,
            Description = chip.Description,
            Image = chip.Image,
            Type = assemblyType
        };
    }
}

It works fine. ChipAssembly is a helper which holds necessary fields + Type which helps me to create instance of it once user asks for it explicitly.

Now, I use binary serialization to save it to a file, including type. When I deserialize it throws SerializationException, saying that AssemblyNamespace.AssemblyClass is not found. However, when I force type to AssemblyClass when serializing, it deserializes correctly. I feel that I somehow assign wrong assemblyType, am I? :)

AssemblyNamespace.AssemblyClass is just an example of loaded assembly.

Upvotes: 0

Views: 252

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

I suspect that you need to load the assembly containing this type into the CLR before attempting to deserialize if this assembly is not statically linked to the executing assembly:

Assembly assembly = Assembly.LoadFile(assemblyPath);
// the assembly containing the type is now loaded into the CLR
// => deserialize now

Upvotes: 1

Related Questions