当我尝试通过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
答案 0 :(得分:1)
从它的外观来看,无论你创建什么类型,都期望构造函数中有一个serviceContext参数。你没有设置它,所以它崩溃了。
答案 1 :(得分:1)
我不知道为什么要以反射方式创建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);