1

当我尝试通过 assembly.CreateInstance 方法创建类型的实例时发生异常。这是我发生异常的代码

Assembly assembly = Assembly.LoadFrom(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.UserProfiles.dll");
Type type = assembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfileManager");
object ins = assembly.CreateInstance(type.FullName);

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->     System.ArgumentNullException: Value cannot be null.
Parameter name: serviceContext
   at Microsoft.Office.Server.UserProfiles.ProfileManagerBase..ctor(SPServiceContext serviceContext)
   at Microsoft.Office.Server.UserProfiles.ProfileManagerBase..ctor(SPServiceContext serviceContext, Boolean ignorePrivacy)
   at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext, Boolean IgnoreUserPrivacy, Boolean backwardCompatible)
   at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor()
   --- End of inner exception stack trace ---
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   at System.Reflection.Assembly.CreateInstance(String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   at System.Reflection.Assembly.CreateInstance(String typeName)
   at HomeWork.Program.Main(String[] args) in c:\users\amasud\documents\visual studio 2010\Projects\HomeWork\HomeWork\Program.cs:line 23
4

2 回答 2

2

我不知道您为什么要以反射方式创建 Microsoft.Office.Server.UserProfiles.UserProfileManager 对象。在您的情况下,您必须将 SPServerContext 传递给构造函数。这是你如何做到的。

Assembly assembly = Assembly.LoadFrom(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.UserProfiles.dll");
SPServiceContext serviceContext = SPServiceContext.Current;
Type type = assembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfileManager");
object ins = Activator.CreateInstance(type, serviceContext);
于 2012-04-27T13:48:30.560 回答
1

从外观上看,您创建的任何类型都需要构造函数中的 serviceContext 参数。你没有设置它,所以它崩溃了。

于 2012-04-27T13:27:46.533 回答