Example #1
0
File: MEF.cs Project: blqw/blqw.IOC
        /// <summary>
        /// 获取插件容器
        /// </summary>
        /// <returns> </returns>
        private static CompositionContainer GetContainer()
        {
            var dir = AppDomain.CurrentDomain.RelativeSearchPath;
            var files = new HashSet<string>(
                Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
                    .Union(Directory.EnumerateFiles(dir, "*.exe", SearchOption.AllDirectories))
                , StringComparer.OrdinalIgnoreCase);
            var catalogs = new AggregateCatalog();
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            var loaded = new HashSet<string>();
            foreach (var a in assemblies)
            {
                if (a.CanLoad() && loaded.TryAdd(a))
                {
                    a.LoadTypes()?.ForEach(catalogs.Catalogs.Add);
                }
                if (a.IsDynamic == false)
                {
                    Uri filePath;
                    if (Uri.TryCreate(a.EscapedCodeBase, UriKind.Absolute, out filePath) && filePath.IsLoopback)
                    {
                        files.Remove(filePath.LocalPath);
                    }
                    files.Remove(a.Location);
                }
            }

            LogServices.Logger?.Write(TraceEventType.Start, $"扫描动态文件 -> 文件个数:{files.Count}");
            if (files.Count > 0)
            {
                var domain = AppDomain.CreateDomain("mef");
                LogServices.Logger?.Write(TraceEventType.Start, "新建临时程序域");
                foreach (var file in files)
                {
                    try
                    {
                        var bytes = File.ReadAllBytes(file);
                        var ass = domain.Load(bytes);
                        if (loaded.TryAdd(ass) && ass.CanLoad())
                        {
                            Assembly.Load(bytes).LoadTypes()?.ForEach(catalogs.Catalogs.Add);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogServices.Logger?.Write(TraceEventType.Error, $"文件加载失败{file}", ex);
                    }
                }
                LogServices.Logger?.Write(TraceEventType.Stop, "卸载程序域");
                AppDomain.Unload(domain);
            }
            LogServices.Logger?.Write(TraceEventType.Stop, "文件处理完成");
            return new SelectionPriorityContainer(catalogs);
        }
        public void op_TryAdd_ICollectionOfT_T_whenTrue()
        {
            var list = new HashSet<string>();

            Assert.True(list.TryAdd("example"));
        }