How to load an assembly from a Stream or byte[] in

2019-02-13 15:58发布

问题:

I want to load an assembly at runtime using either a Stream or a Byte array.

In .net you can use Assembly.Load(Byte[], Byte[]) http://msdn.microsoft.com/en-us/library/twt16z2x.aspx

In standard Silverlight you can use AssemblyPart.Load() http://msdn.microsoft.com/en-us/library/cc190521%28v=VS.96%29.aspx

But in Windows Phone 7 neither of these methods are avaliable.

回答1:

Well, as you pretty much discovered; you can't do it. The design doesn't allow for you to load an assembly that doesn't ship in your XAP. This is a security design, since they don't want you downloading and running arbitrary code that hasn't passed Marketplace Inspection.

This is on par with how Apple controls its App Store. Why this functionality is not there, and why I doubt it will be added:

  1. Marketplace. Microsoft requires that all Applications pass a blackbox inspection. They likely look for a number of things, such as performance, major bugs, risqué material, and UI consistency. Allowing a developer to load and run any assembly completely circumvents the Marketplace. That hurts the user in a few ways. The first being that a developer would be tempted to use it as a means of distributing updates outside of the Marketplace, or sneaking in features (Like porn) that Microsoft doesn't allow on their Marketplace.
  2. Security. Being able to load an assembly is a powerful feature, that can be both good and bad. If a developer implemented it incorrectly, it might be possible to exploit it. Secondly, it might have been a technical limitation (or time limitation) on Microsoft for how it would affect sandboxing of apps. Or worse, a seemingly harmless application downloads a different assembly after it already passed inspection, then starts doing something nefarious; like key logging and uploading it somewhere. Since it went around the Marketplace, Microsoft would never have been able to catch it before it went to the public.

What you can do, as OJ suggested in the comments, is make the assemblies as part of your XAP, and use one of the Assembly.Load overloads that allow you to load it by name. You can dynamically load assemblies, they just have to be a part of your XAP.