C# 如何使用依赖项注入正确管理这种情况
想象一下,你有一个网站,每个用户都可以把一个代码放在一个框中,然后按“搜索”来查找有关产品的信息。代码将与模式匹配:C# 如何使用依赖项注入正确管理这种情况,c#,dependency-injection,castle-windsor,C#,Dependency Injection,Castle Windsor,想象一下,你有一个网站,每个用户都可以把一个代码放在一个框中,然后按“搜索”来查找有关产品的信息。代码将与模式匹配:SHOPNAME-PROGRESSIVENUMBER,例如:EVERYDAYSHOES-002,或NEWGAMES-005 当用户按下“搜索”按钮时,我的代码将: 识别商店 获取连接到DB的连接字符串,这对于每个商店都是不同的 使用该连接字符串在该数据库上调用查询 我想到的第一件事就是编写如下代码: public interface IProductInformationsProv
SHOPNAME-PROGRESSIVENUMBER
,例如:EVERYDAYSHOES-002
,或NEWGAMES-005
当用户按下“搜索”按钮时,我的代码将:
public interface IProductInformationsProvider
{
string GetProductName(int productCode);
}
public class SQLProductInformationsProvider : IProductInformationsProvider
{
...
public SQLProductInformationsProvider(
string connectionString,
ILogService logService)
{
...
}
public string GetProductName(int productCode)
{
...
}
}
要获得IPProductInformationsProvider
的距离,我将使用DI容器并执行以下操作:
public interface IProductInformationsProvider
{
string GetProductName(int productCode);
}
public class SQLProductInformationsProvider : IProductInformationsProvider
{
...
public SQLProductInformationsProvider(
string connectionString,
ILogService logService)
{
...
}
public string GetProductName(int productCode)
{
...
}
}
public void SearchButtonHandler(字典商店连接字符串映射)
{
使用(var container=new WindsorContainer())
{
集装箱。登记(
用于()的组件
.ImplementedBy());
集装箱。登记(
用于()的组件
.由()实施
德彭森先生(
OnValue(“connectionString”,shopsConnectionStringsMap[parsedShopName]);
var productInformationsProvider=container.Resolve();
var productName=productInformationsProvider.GetProductName(代码);
//使用productName执行某些操作
}
}
我的问题是:
connectionString
SQLProductInformationsProvider
,将它们缓存在字典中并使用所需的字典connectionString
,并将其放在方法SetConnectionString(stringconnectionstring)
上,但在这种情况下,我必须更加担心线程安全所有这三个想法都不能让我满意,它们让我觉得我误解了什么。我缺少什么/我怎样才能改变我的观点?我认为一个解决方案是:
public interface IProductInformationsProvider
{
string GetProductName(int productCode);
}
public interface IConnectionStringProvider
{
string GetConnectionString(string shopName);
}
public class SQLProductInformationsProvider : IProductInformationsProvider
{
...
public SQLProductInformationsProvider(
IConnectionStringProvider connectionStringProvider,
ILogService logService)
{
...
}
public string GetProductName(string shopName, int productCode)
{
string connectionString = connectionStringProvider.GetConnectionString(shopName);
...
}
}
public void SearchButtonHandler(string shopName, int Code)
{
// _productInformationsProvider already resolved
var productName = _productInformationsProvider.GetProductName(shopName, Code);
// Do something with productName
}
使用容器先注册具体类型,然后在下一行中解析是没有意义的。容器在这里引入了什么值,而不是在这两种类型上调用
new
?您如何通过构造函数传递\u shopsConnectionStringsMap
?您现在可以展示构造函数的外观吗?