RevitCoreContext.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /* ==============================================================================
  2. * 功能描述:RevitCoreContext
  3. * 创 建 者:Garrett
  4. * 创建日期:2019/6/27 11:10:20
  5. * ==============================================================================*/
  6. using Autodesk.Revit;
  7. using Autodesk.Revit.ApplicationServices;
  8. using Autodesk.Revit.DB;
  9. using SAGA.DotNetUtils.Revit;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Reflection;
  15. namespace ExportStart
  16. {
  17. public class RevitCoreContext
  18. {
  19. // 此路径为动态反射搜索路径 、 此路径可为任意路径(只要路径下有RevitNET 所需依赖项即可,完整依赖项可在 Naviswork 2016 下面找到)
  20. private static readonly string[] Searchs = RevitUtils.GetSearchPath().ToArray();
  21. static readonly object lockobj = new object();
  22. static RevitCoreContext _instance;
  23. private Product _product;
  24. public Application Application { get => _product.Application; }
  25. public static RevitCoreContext Instance
  26. {
  27. get
  28. {
  29. if (_instance == null)
  30. {
  31. lock (lockobj)
  32. {
  33. if (_instance == null)
  34. {
  35. _instance = new RevitCoreContext();
  36. }
  37. }
  38. }
  39. return _instance;
  40. }
  41. }
  42. static RevitCoreContext()
  43. {
  44. AddEnvironmentPaths(Searchs);
  45. AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
  46. }
  47. public void Run()
  48. {
  49. _product = Product.GetInstalledProduct();
  50. var clientId = new ClientApplicationId(Guid.NewGuid(), "DotNet", "BIMAPI");
  51. // I am authorized by Autodesk to use this UI-less functionality. 必须是此字符串。 Autodesk 规定的.
  52. _product.Init(clientId, "I am authorized by Autodesk to use this UI-less functionality.");
  53. }
  54. public void Stop()
  55. {
  56. _product?.Exit();
  57. }
  58. static void AddEnvironmentPaths(params string[] paths)
  59. {
  60. var path = new[] { Environment.GetEnvironmentVariable("PATH") ?? string.Empty };
  61. //加在最前面,
  62. var newPath = string.Join(System.IO.Path.PathSeparator.ToString(), paths.Concat(path));
  63. Environment.SetEnvironmentVariable("PATH", newPath);
  64. }
  65. private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
  66. {
  67. var assemblyName = new AssemblyName(args.Name);
  68. foreach (var item in Searchs)
  69. {
  70. var file = string.Format("{0}.dll", System.IO.Path.Combine(item, assemblyName.Name));
  71. if (File.Exists(file))
  72. {
  73. try
  74. {
  75. return Assembly.LoadFile(file);
  76. }
  77. catch (Exception e)
  78. {
  79. Console.WriteLine(e);
  80. }
  81. }
  82. }
  83. return args.RequestingAssembly;
  84. }
  85. }
  86. }