我的静态方法是否会向调用它的每个对象返回一个新的EF上下文?

时间:2014-07-17 10:15:27

标签: c# entity-framework object static

假设我有一个WCF服务,它在每个WCF调用上创建一个单独的RuleController实例:

public class RuleController
{
    private PresenceEntities _context;

    public RuleController()
    {
        _context = ContextCreator.GetEFContext();
    }
 }

这是ContextCreator:

public static class ContextCreator
{
   public static PresenceEntities GetEFContext()
   {
     // Retrieve database configuration
     var modelFilePath = ConfigurationManager.AppSettings["ModelFilePath"];
     var connectionProvider = ConfigurationManager.AppSettings["ConnectionProvider"];
     var connectionString = ConfigurationManager.AppSettings["ConnectionString"];

     var builder = new EntityConnectionStringBuilder();
     builder.Metadata = modelFilePath;
     builder.Provider = connectionProvider;
     builder.ProviderConnectionString = connectionString;

     var edmConnectionString = builder.ToString();
     return new PresenceEntities(edmConnectionString);
   }
}

如果我以这种方式使用静态方法,RuleController的每个实例都会获得自己的实体框架上下文实例吗? 我想是的,因为_context的引用是在RuleController中保存的,但我并不是100%肯定。

编辑:修改后的GetEFContext方法,包括构建连接字符串的部分。

1 个答案:

答案 0 :(得分:0)

是的,因为

    public static PresenceEntities GetEFContext()
    {
        var edmConnectionString = [connection string here]
        return new PresenceEntities(edmConnectionString); //THIS LINE !!
    }

在这里,您只需在每次通话时创建一个新实例。