我们有一个连接到数据库的WCF REST服务。实际上,我们有几个数据库实例,都具有相同的模式。
我们希望为每个数据库实例设置一个端点,并将连接字符串与端点相关联。该服务将读取连接字符串并连接到相应的SQL Server实例。
我确信这是可能的;这是个好主意吗?我该如何设置? MSDN上有文档吗?
修改:我找到this question,答案建议在标头中添加客户端的连接信息。出于安全原因,我不想这样做,因为我做想要为每个数据库设置一个独特的uri。
答案 0 :(得分:2)
这比我想象的要困难一些。 WCF有这么多扩展点,很难选择正确的。如果您认为有更好的方法,或者有任何问题,请回答或评论。
我已经决定使用实现IEndpointBehavior和IDispatchMessageInspector的自定义类。我有一个派生自BehaviorExtensionElement的类,它允许我将行为与配置中的端点相关联。 This blog post描述了hot do do that。
我的DatabaseConnectionContext
课程如下:
/// <summary>
/// An endpoint behavior that associates a database connection string name with the endpoint and adds it to the
/// properties of incoming messages.
/// </summary>
public class DatabaseConnectionContext : IEndpointBehavior, IDispatchMessageInspector
{
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseConnectionContext"/> class with the provided connection string name.
/// </summary>
/// <param name="connectionStringName">The name of the connection string to associate with the endpoint.</param>
public DatabaseConnectionContext(string connectionStringName)
{
this.ConnectionStringName = connectionStringName;
}
/// <summary>
/// Gets the name of the connection string to associate with the endpoint.
/// </summary>
public string ConnectionStringName { get; private set; }
/// <inheritdoc />
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
/// <inheritdoc />
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
/// <inheritdoc />
public void Validate(ServiceEndpoint endpoint)
{
}
/// <inheritdoc />
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
request.Properties["connectionStringName"] = this.ConnectionStringName;
return null;
}
/// <inheritdoc />
public void BeforeSendReply(ref Message reply, object correlationState)
{
}
}
在我的服务类中,我有这个方法:
/// <summary>
/// Returns the connection string to use for this service call.
/// </summary>
/// <returns>A SQL Server database connection string.</returns>
private string GetConnectionString()
{
string connectionStringName = (string)OperationContext.Current.IncomingMessageProperties["connectionStringName"];
return ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
我的BehaviorExtensionElement
课程如下:
/// <summary>
/// Associates a <see cref="DatabaseConnectionContext"/> with an endpoint in configuration.
/// </summary>
public class DatabaseConnectionContextBehaviorExtension : BehaviorExtensionElement
{
/// <summary>
/// The name of the <see cref="ConnectionStringName"/> property when it appears in a configuration file.
/// </summary>
private const string ConnectionStringNamePropertyName = "connectionStringName";
/// <summary>
/// Gets or sets the name of the configuration string to associate with the endpoint.
/// </summary>
[ConfigurationProperty(ConnectionStringNamePropertyName)]
public string ConnectionStringName
{
get
{
return (string)this[ConnectionStringNamePropertyName];
}
set
{
this[ConnectionStringNamePropertyName] = value;
}
}
/// <inheritdoc />
public override Type BehaviorType
{
get { return typeof(DatabaseConnectionContext); }
}
/// <inheritdoc />
protected override object CreateBehavior()
{
return new DatabaseConnectionContext(this.ConnectionStringName);
}
}
我的web.config包含以下内容:
<behaviors>
<endpointBehaviors>
<behavior name="DevRestEndpointConfiguration">
<webHttp helpEnabled="false" />
<connectionStringInterceptor connectionStringName="myDevConnectionStringName" />
</behavior>
<behavior name="ProductionRestEndpointConfiguration">
<webHttp helpEnabled="false" />
<connectionStringInterceptor connectionStringName="myProductionConnectionStringName" />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="connectionStringInterceptor" type="DatabaseConnectionContextBehaviorExtension, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
<endpoint />
部分中的每个<services />
元素都将behaviorConfiguration
设置为<endpointBehaviors />
部分中相应元素的名称。
答案 1 :(得分:1)
为什么不添加一个新参数来指定调用将连接的数据库?
例如:
db
参数,这些参数将获得一个数字,然后您将连接作为第一项的示例:
public ProductItem GetProduct(int productId, int db = 1)
{
ProductItem product = new ProductItem();
string connectionString = getConnectionStringForDb(db);
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT name, price FROM Products WHERE productId = @product;", connection);
command.Parameters.AddWithValue("@product", productId);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
reader.Read();
product = new product({
Name = reader[0],
Price = reader[1]
});
reader.Close();
}
catch (Exception ex)
{
// Log exception
}
}
return product;
}
private string getConnectionStringForDb(int type)
{
System.Configuration.ConnectionStringSettings connString;
System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) {
connString = rootWebConfig.ConnectionStrings.ConnectionStrings["DBConnectionString_" + type];
if (connString == null) {
// LOG ERROR
}
}
return connString.ConnectionString;
}
然后只需在web.config
中添加连接字符串,然后输入名称:
DBConnectionString_1, DBConnectionString_2, DBConnectionString_3
或任何对你有意义的事情。
<connectionStrings>
<add
name="DBConnectionString_1"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
<add
name="DBConnectionString_2"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
<add
name="DBConnectionString_3"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
答案 2 :(得分:0)
在你的web.config中使用它:
<configuration>
<appSettings>
<add key="Foo.svc" value="tagvalue1"/>
</appSettings>
...
您可以通过以下方式在运行时检索值:
private static string GetConfigValue()
{
ServiceEndpointCollection ec = OperationContext.Current
.Host.Description.Endpoints;
if (ec!=null)
{
var segments = ec[0].Address.ToString().Split('/');
var s = segments[segments.Length-1]; // "Foo.svc"
return ConfigurationManager.AppSettings[s]; // "tagvalue1"
}
return null;
}