我们有一个托管在 ASP.NET MVC WebAPI 中的应用程序,它使用外部托管库。此托管库再次使用 COM 库。COM 库是许多应用程序和不同版本中使用的通用库,因此我们希望能够通过直接从 bin 文件夹加载它来并行运行它,而不是使用传统的 COM 注册。我们通过添加清单文件并调用 kernel32.dll 中的 CreateActCtx 来注册自定义激活上下文(代码包含在下面)来实现这一点。
这本身就可以正常工作,但是当我们在加载 COM 库之前将 Thread.CurrentPrincipal 设置为具有自定义 IIdentity 实现的 GenericPrincipal 实例时,我们会收到一个 <CrtImplementationDetails>.ModuleLoadException 消息“C++ 模块在尝试加载时失败初始化默认的应用程序域。”。它有一个内部 System.Runtime.Serialization.SerializationException 表示它无法加载实际上启动 COM 程序集加载的程序集。堆栈跟踪是:
Server stack trace:
at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeObject(MemoryStream stm)
at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage.FixupForNewAppDomain()
at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoDispatch(Byte[] reqStmBuff, SmuggledMethodCallMessage smuggledMcm, SmuggledMethodReturnMessage& smuggledMrm)
at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoTransitionDispatchCallback(Object[] args)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System.AppDomain.get_Id()
at <CrtImplementationDetails>.DoCallBackInDefaultDomain(IntPtr function, Void* cookie)
at <CrtImplementationDetails>.LanguageSupport._Initialize(LanguageSupport* )
at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
--- End of inner exception stack trace ---
at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
at .cctor()
--- End of inner exception stack trace ---
当我们不设置 Thread.CurrentPrincipal 或使用带有 GenericIdentity 的 GenericPrincipal 时,它可以正常工作。目前,使用 GenericIdentity 的解决方案是我们的解决方法,因为我们主要设置 Thread.CurrentPrincipal 以使用 ASP.NET MVC 身份验证。
以下代码有效:
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("bla"), new string[0]);
...而以下没有:
Thread.CurrentPrincipal = new GenericPrincipal(new CustomIdentity("bla"), new string[0]);
以下是用于注册自定义激活上下文的 global.asax 代码,引用 bin 文件夹和清单文件以执行无注册 COM:
public class Global : System.Web.HttpApplication
{
private const UInt32 ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET = 14011;
IntPtr hActCtx;
private static readonly ILogger s_logger = LogManager.GetCurrentClassLogger();
protected void Application_Start(object sender, EventArgs e)
{
// Required files are copied in host projects post-build event
// NB! you can only set the default activation context like this once per app domain,
// so if you need multiple apps/services using side-by-side they cannot share app pool.
UInt32 dwError = 0;
string binDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"bin");
string manifestPath = Path.Combine(binDirectory, "Iit.OpenApi.Services.ReferenceData.manifest");
var activationContext = new ACTCTX();
activationContext.cbSize = Marshal.SizeOf(typeof(ACTCTX));
activationContext.dwFlags = ACTCTX_FLAG_SET_PROCESS_DEFAULT | ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;
activationContext.lpSource = manifestPath;
activationContext.lpAssemblyDirectory = binDirectory;
hActCtx = CreateActCtx(ref activationContext);
if (hActCtx.ToInt32() == -1)
{
dwError = (UInt32)Marshal.GetLastWin32Error();
}
if ((hActCtx.ToInt32() == -1) && (dwError != Global.ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET))
{
var err = string.Format("Cannot create process-default win32 sxs context, error={0} manifest={1}", dwError, manifestPath);
throw new ApplicationException(err);
}
// TODO: add eventid to enum
if ((hActCtx.ToInt32() == -1) && (dwError == Global.ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET))
{
GetCurrentActCtx(out hActCtx);
s_logger.Info(9998, string.Format("Re-using exising ActivationContext [{0}].", hActCtx.ToInt64()));
}
else
{
s_logger.Info(9998, string.Format("ActivationContext [{0}] created successfully.", hActCtx.ToInt64()));
}
}
protected void Application_End()
{
if (hActCtx.ToInt64() != INVALID_HANDLE_VALUE)
{
ReleaseActCtx(hActCtx);
// TODO: add eventid to enum
s_logger.Info(9999, string.Format("ActivationContext [{0}] released successfully.", hActCtx.ToInt64()));
}
}
[StructLayout(LayoutKind.Sequential)]
private struct ACTCTX
{
public int cbSize;
public uint dwFlags;
public string lpSource;
public ushort wProcessorArchitecture;
public ushort wLangId;
public string lpAssemblyDirectory;
public string lpResourceName;
public string lpApplicationName;
}
private const uint ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004;
private const uint ACTCTX_FLAG_SET_PROCESS_DEFAULT = 0x010;
private const Int64 INVALID_HANDLE_VALUE = -1;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateActCtx(ref ACTCTX actctx);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetCurrentActCtx(out IntPtr hActCtx);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern void ReleaseActCtx(IntPtr hActCtx);
}
关于使用自定义 IIdentity 时出了什么问题的任何输入,以及如何使其与无 reg-free COM 一起工作?