如何使WCF设置连接字符串以与EntityFramework一起使用

时间:2014-07-19 21:04:57

标签: c# entity-framework wcf

使用EntityFramework,我有一个自动生成的文件:

namespace Chaos.Data    
{
public partial class ChaosModel : OpenAccessContext, IChaosModelUnitOfWork
{
    private static string connectionStringName = @"ChaosLibraryConnection";

    private static BackendConfiguration backend = GetBackendConfiguration();

    private static MetadataSource metadataSource = XmlMetadataSource.FromAssemblyResource("EntitiesModel.rlinq");

    public ChaosModel()
        :base(connectionStringName, backend, metadataSource)
    { }

    public ChaosModel(string connection)
        :base(connection, backend, metadataSource)
    { }

     ......................

在WCF服务中,我正在使用:

namespace Chaos.DataService
{
[ServiceContract]
public class ChaosService 
{
    [OperationContract]
    public IEnumerable<Encountertime> GetEncounterTimes(DateTime? encountertime)
    {
        if (encountertime == null) return null;

        using (var context = new ChaosModel())
        {
            var query = from et in context.Encountertimes
                        where et.Tencounter.Date == ((DateTime)encountertime).Date
                        select et;

           var result = context.CreateDetachedCopy(query.ToList());
            return result;
        }
    }
 .............................

如何在启动时使WCF服务执行一个方法(一次),该方法将返回一个新的连接字符串,以便我可以将对ChaosModel()的调用更改为:

using (var context = new ChaosModel(connectionString))

(我正在寻找一种在WCF服务中添加静态构造函数的方法 - 还是更好的东西?)。

(该方法将确定我所在的网络,并为网络服务器构建适当的连接字符串。)

注意:我无法更改自动生成的Entity文件。

1 个答案:

答案 0 :(得分:2)

使用静态构造函数。

[ServiceContract]
public class ChaosService 
{
    private static string connectionString;

    static ChaosService(){
        connectionString = your logic...
    }

    [OperationContract]
    public IEnumerable<Encountertime> GetEncounterTimes(DateTime? encountertime)
    {
        using (var context = new ChaosModel(connectionString))
        {
           ...
        }
    }
}

或最终是单身人士模式:

public class ConnectionInfo
{
    public string ConnectionString { get; private set; }

    private ConnectionInfo()
    {
        var connectionstring = string.Empty;
        //some logic

        this.ConnectionString = connectionstring;
    }

    private static ConnectionInfo current;

    public static ConnectionInfo Current {
        get {
            if (current != null)
                current = new ConnectionInfo();

            return current;
        }
    }
}        

[OperationContract]
public IEnumerable<Encountertime> GetEncounterTimes(DateTime? encountertime)
{
    using (var context = new ChaosModel(ConnectionInfo.Current.ConnectionString))
    {
       ...
    }
}