【发布时间】:2013-07-08 05:17:27
【问题描述】:
我有一个 WCF 服务,我正在尝试遵循依赖倒置原则。我有一些疑问并在下面列出。 依赖原理之前和依赖原理之后的代码如下..
代码依赖原则:-
INodeAppService.cs
namespace MyAppService
{
public class Nodes
{
[DataMember]
public int NodeID { get; set; }
[DataMember]
public string Item { get; set; }
}
[ServiceContract]
public interface INodeAppService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
List<Nodes> GetNodes(); //changed
}
}
NodeAppService.svc.cs
namespace MyAppService
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class NodeAppService: INodeAppService
{
public List<Nodes> GetNodes()
{
List<Nodes> nodeList = new List<Nodes>(); //changed
SqlCommand sqlCommand = new SqlCommand("myquery", conn);
SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
DataTable dt = new DataTable();
try
{
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
Nodes node= new Nodes();
node.NodeID = Convert.ToInt32(row["NodeID"]);
node.Item = row["Item"].ToString();
nodeList.Add(node); //changed
}
return nodeList;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
}
}
依赖原则后的代码:-
INodeAppService.cs
namespace MyAppService
{
public class Nodes
{
[DataMember]
public int NodeID { get; set; }
[DataMember]
public string Item { get; set; }
}
[ServiceContract]
public interface INodeAppService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
IList<Nodes> GetNodes(); // List changed to IList
}
}
NodeAppService.svc.cs
namespace MyAppService
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class NodeAppService: INodeAppService
{
private IList<Nodes> _nodeList;
public NodeAppService(IList<Nodes> nodeList)
{
_nodeList= nodeList;
}
public IList<Nodes> GetNodes()
{
SqlCommand sqlCommand = new SqlCommand("myquery", conn);
SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
DataTable dt = new DataTable();
try
{
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
Nodes node= new Nodes(); // How can I remove this dependency?
node.NodeID = Convert.ToInt32(row["NodeID"]);
node.Item = row["Item"].ToString();
_nodeList.Add(node);
}
return _nodeList;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
}
}
1) 但我收到错误“提供的服务类型无法作为服务加载,因为它没有默认(无参数)构造函数。要解决此问题,请向该类型添加默认构造函数,或者将类型的实例传递给主机”。
但是提供默认参数并不能解决我的问题。请给出解决问题的方法。
2) 节点 node= new Nodes(); // 我怎样才能删除这个依赖? [请看代码]
3) 依赖倒置原则和wcf是好方法吗?
谢谢。
我能够使用名为“Castle Windsor”的依赖注入容器来实现依赖倒置原则。但在我的情况下,创建 Nodes 类的对象似乎不被称为“依赖”。
List<Nodes> nodeList = new List<Nodes>();
我是这样读的。
“仅数据对象通常不称为“依赖项”,因为它们不执行某些需要的功能。”有什么想法吗?
谢谢。
【问题讨论】:
-
你使用的是什么依赖注入容器?
-
“依赖注入容器”是什么意思。无论如何,我正在通过构造函数添加依赖注入..
-
我不知道有任何“依赖注入容器”。现在我尝试使用“Castle Windsor”并且它正在工作。谢谢您的帮助。 prideparrot.com/blog/archive/2012/2/…
标签: wcf solid-principles dependency-inversion