silverlight动态加载(研究与探讨)

网络上流传的是sl动态加载xap包来实现silverlight程序动态加载

它的代码:

    // 可以通过 Deployment.Current 检索 AppManifest.xaml 中的 Deployment 对象

            // 取得 XAP 的 AppManifest.xaml 中的 Deployment.Parts 内的全部 AssemblyPart 节点信息
            StreamResourceInfo resource = App.GetResourceStream(new StreamResourceInfo(e.Result, null),new Uri("AppManifest.xaml", UriKind.Relative));
            string resourceManifest = new StreamReader(resource.Stream).ReadToEnd();
            List<XElement> assemblyParts = XDocument.Parse(resourceManifest).Root.Elements().Elements().ToList();

            //加载程序集
            Assembly assembly = null;
            foreach (XElement element in assemblyParts)
            {
                // 取出 AssemblyPart 的 Source 指定的 dll
                string source = element.Attribute("Source").Value;
                AssemblyPart assemblyPart = new AssemblyPart();
                StreamResourceInfo streamInfo = App.GetResourceStream(new StreamResourceInfo(e.Result, "application/binary"),new Uri(source, UriKind.Relative));
                if (source == ProjectName + ".dll")
                {
                    assembly = assemblyPart.Load(streamInfo.Stream);
                }
                else
                {
                    //释放dll
                    assemblyPart.Load(streamInfo.Stream);
                }
            }

    object o = assembly.CreateInstance(TypeName);

但我实验过,动态加载dll的话

     AssemblyPart assemblyPart = new AssemblyPart();
            Assembly assembly = assemblyPart.Load(e.Result);

            object o = assembly.CreateInstance(TypeName);

 三行代码就实现了动态加载程序集,然而加载的容量:

 

再看一下xap包中的东西:

管用的只有Sample2.dll这一个东西,居然把所有dll打包到xap,再传到客户端,多此一举,另外还增加了解析xap这步骤.(不过加载xap也能实现)

我觉得动态加载xap这个方法可以用到局部使用了silverlight的网页,而如果是全部silverlight的话应该动态加载dll来实现.Sample2.dll是集项目所有用到的dll的集合的打包体.这是我这几天研究silverlight动态加载的一些体会.

还有未解决的就是:如果是app.xaml里写的资源文件,好像读不到,希望大家一起讨论

我的实现代码:1.先webclient下载dll

                            TypeName = code[0];
                            Uri uri = new Uri(ProjectPath + code[2] + ".dll");
                            WebClient client = new WebClient();
                            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
                            client.OpenReadAsync(uri);

                  2.异步得到dll的stream,然后再反射出来到界面

                           void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
                          {
                               AssemblyPart assemblyPart = new AssemblyPart();
                               Assembly assembly = assemblyPart.Load(e.Result);

                               object o = assembly.CreateInstance(TypeName);

                         }

posted @ 2009-10-28 14:40  D调dě浪漫  阅读(2172)  评论(4编辑  收藏  举报