PLUGIN中初始化Service-IOrganizationServiceFactory.CreateOrganizationService 方法
在检查PLUGIN代码的时候发现如下一段获取组织服务的代码
// service provider.
this.Context =(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// 访问组织服务
IOrganizationServiceFactory factory =(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
this.Service = factory.CreateOrganizationService(this.Context.UserId);
this.TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
this.AdminService = factory.CreateOrganizationService(getAdminId());
一般我们在初始化Service的时候都是用的Context.UserId来初始化,也就是当前执行用户的身份。
但这里出现了一个AdminService,也就是强制用管理员的身份来初始化,实现方法是通过getAdminId()方法来获取admin的Id
Guid getAdminId()
{
string fetch = string.Format(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='systemuser'>
<attribute name='fullname' />
<attribute name='businessunitid' />
<attribute name='title' />
<attribute name='address1_telephone1' />
<attribute name='systemuserid' />
<order attribute='fullname' descending='false' />
<filter type='and'>
<condition attribute='fullname' operator='eq' value='crmadmin1名' />
</filter>
</entity>
</fetch> ");
EntityCollection enities = Query.query.QueryByFetch(fetch, Service);
//TracingService.Trace("enities.Entities.Count:" + enities.Entities.Count.ToString());
if (enities.Entities.Count > 0)
{
//TracingService.Trace(enities.Entities[0].Id.ToString());
return enities.Entities[0].Id;
}
else
{
return Guid.Empty;
}
}
检查系统发现,系统中根本没有叫crmadmin1名的用户,也就是永远返回一个Guid.Empty,原以为这样会报错,但实际情况却是正常,没有报错出现。查询微软文档发现如下一段解释
IOrganizationService CreateOrganizationService (
Nullable<Guid> userId
)
参数
userId
Type: 可为空值. Specifies the system user that calls to the service are made for. A Null value indicates the SYSTEM user. When called in a plug-in, a Guid.Empty value indicates the same user as IPluginExecutionContext. UserId. When called in a custom workflow activity, a Guid.Empty value indicates the same user as IWorkflowExecutionContext.UserId. Any other value indicates a specific system user.
也就是说可以直接传递一个Guid.Empty来初始化Service,并且如果是Guid.Empty那么其实和Context.UserId是同样的作用。