【问题标题】:On how I access my DataContext (and whether it's wrong)关于我如何访问我的 DataContext(以及它是否错误)
【发布时间】:2012-02-21 01:11:42
【问题描述】:

我使用下面的 static class 来访问我的应用程序中的数据上下文

public static class DataContext
{
    internal const string _contextDataKey = "dataContext";

    /// <summary>
    /// Returns a unique data context that lives for the duration of the request, which can be from ASP.NET or a WCF service
    /// </summary>
    /// <returns>The entity data model context for the current request</returns>
    public static EntityDataModelContext GetDataContext()
    {
        IPersistanceContainer state;

        if (HttpContext.Current != null)
        {
            state = new AspNetPersistanceContainer();
        }
        else if (OperationContext.Current != null)
        {
            state = new WcfPersistanceContainer();
        }
        else
        {
            state = new StaticPersistanceContainer(); // this container is thread-unsafe.
        }

        EntityDataModelContext edm = state.Get<EntityDataModelContext>(_contextDataKey);
        if (edm == null)
        {
            edm = new EntityDataModelContext();
            state.Store(_contextDataKey, edm);
        }

        return edm;
    }
}

忘记其他容器,它们分别用于WCFConsole 应用程序简单测试,这里是ASP.NET 容器:

internal class AspNetPersistanceContainer : IPersistanceContainer
{
    public T Get<T>(string key) where T : class
    {
        if (HttpContext.Current.Items.Contains(key))
            return (T)HttpContext.Current.Items[key];

        return null;
    }

    public void Store(string key, object value)
    {
        HttpContext.Current.Items[key] = value;
    }
}

当我需要访问context 时,我只需调用DataContext.GetDataContext() 并进行数据库访问,我从不添加任何using 语句。

如果我添加一个using 语句,context 适合一次使用,下次我尝试使用它时,它会被丢弃。引发异常。

如果我不这样做,就像现在一样,这会让我有点不开心,我觉得这也不是正确的做法,不处理它。

所以我想知道在这里做什么是正确的。

这个设计有缺陷吗,我应该完全放弃它吗?

我是否应该想办法在上下文被处理掉时重新创建它?

我应该让设计保持原样吗?可以吗?

也许设计“足够好”,你有什么书可以推荐我阅读吗?我觉得我在后端架构方面的技能相当欠缺。

【问题讨论】:

    标签: c# model-view-controller design-patterns


    【解决方案1】:

    在 asp.net 应用程序中,一种解决方案可能是这样的:

    1. 在请求开始时创建上下文
    2. 在请求结束时释放它

    Here 的文章讨论了这种方法(对于 NHibernate 会话管理,但对于 EF 几乎相同)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-05-24
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 2017-02-14
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多