【问题标题】:How to implement a using statement when inititializing a service?初始化服务时如何实现 using 语句?
【发布时间】:2016-02-24 09:37:36
【问题描述】:

概述:

我在 XRM 项目中遇到了一些初始化代码,其中正在初始化的实例实现了 IDisposible,但实例上没有围绕 using 块。

looked at 的示例中,在 using 块内有一个在服务上调用的实例方法。但在我下面的例子中,服务实例刚刚被初始化。直到在私有方法的代码中进一步调用服务方法本身才会被调用。

问题:

如何使用 using 块进行服务实例初始化?

代码示例 1:(服务初始化)

public static void Init(string connectionString, string name)
{
    instanceName = name;
    CreateSourceServiceObjects(connectionString);
}

//Service instances just Init here no methods are called:
private static void CreateSourceServiceObjects(string connectionString)
{
    var connection = CrmConnection.Parse(connectionString);        
    sourceService = new OrganizationService(connection);
    sourceContext = new OrganizationServiceContext(sourceService);
}

//Example of where the sourceService method's are used:
public static Entity GetUserInfo(Guid userId)
{
     Entity systemuser = sourceService.Retrieve("systemuser", userId, new ColumnSet(true));
      return systemuser;
}

代码示例2:(我尝试实现using语句)

private static void CreateSourceServiceObjects(string connectionString)
{
    var connection = CrmConnection.Parse(connectionString);

    //Added a Using block to auto dispose OrganizationService and OrganizationServiceContext
    using(sourceService = new OrganizationService(connection))
    using (sourceContext = new OrganizationServiceContext(sourceService))
    {
        //should there be any code in here?

    }

}

【问题讨论】:

    标签: c# dynamics-crm idisposable using-statement xrm


    【解决方案1】:

    您似乎对using 语句有一些误解。 using 语句只能在从创建到处理服务的代码是范围本地的情况下使用。

    您问题中的情况是,服务对象的生命周期超出了创建对象的范围。因此,您的选择是重新设计(为每次调用 GetUserInfo 创建一个新的服务对象)或在不借助 using 语句的情况下管理服务生命周期。

    MSDN Reference 中描述了 using 语句的等效项,并说,

    using (Font font1 = new Font("Arial", 10.0f)) 
    {
        byte charset = font1.GdiCharSet;
    }
    

    的简写形式
    {
        Font font1 = new Font("Arial", 10.0f);
        try
        {
            byte charset = font1.GdiCharSet;
        }
        finally
        {
            if (font1 != null)
                ((IDisposable)font1).Dispose();
        }
    }
    

    通常情况下,使用IDisposable 实现类是一种方式。但是,在您的情况下,您有静态方法和静态变量。所以第一个问题是,你期望的服务寿命是多少?静态变量的默认答案是:“只要应用程序正在运行”,然后就很清楚了,您必须做什么才能确保正确清理:

    • 如果多次调用CreateSourceServiceObjects,请确保在重新分配之前处理旧服务对象或拒绝重新初始化
    • 根据您的程序类型,挂钩到应用程序出口并手动处置服务对象(如果已分配)

    我想指出,通过将类重新设计为非静态的,您可以在这里赢得很多。使用您的类的实例,您可以使用标准的IDisposable 模式,这可能比某些自定义程序退出清理代码更安全。

    说了这么多,如果你的服务已经正确实现了 dispose 和 finalize 功能,你根本不需要担心 dispose,因为你的静态对象会一直存在到应用程序退出,然后通过终结器释放非托管资源。

    【讨论】:

    • 好吧,那是有道理的。
    猜你喜欢
    • 2010-12-22
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2016-03-23
    • 2015-10-28
    • 1970-01-01
    相关资源
    最近更新 更多