【发布时间】:2019-05-04 14:06:08
【问题描述】:
我对 DI 很陌生,所以我的知识并不是最丰富的。我目前正在开发一个 Asp.Net Core MVC 应用程序。
假设我有一个返回 DataSet 的 DLL(我可以完全控制这个 DLL 并且可以根据需要更改它)。
所以 DLL 中的代码如下所示:
public class DataStore : IDataStore
{
private readonly IConfiguration _configuration;
public DataStore(IConfiguration configuration)
{
_configuration = configuration;
}
public DataSet GetDataBySP(string spName, SqlParameter[] parameters = null)
{
DataSet ds = new DataSet();
using(var con = new SqlConnection(_configuration.GetConnectionString("conStr")))
{
using(var cmd = new SqlCommand(spName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parameters?.Length > 0)
cmd.Parameters.AddRange(parameters);
con.Open();
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;
}
}
现在假设我有一个名为 Foo 的类,它只包含如下两个属性:
public interface IFoo
{
Foo GetFooData();
}
public class Foo : IFoo
{
private readonly IDataStore _dataStore;
public int CurrentCount { get; set; }
public int MaxCount { get; set; }
public Foo(DataRow dr)
{
CurrentCount = dr.Field<int>("CurrentCount");
MaxCount = dr.Field<int>("MaxCount");
}
public Foo(IDataStore dataStore)
{
_dataStore = dataStore;
}
}
在Foo我有一个叫GetFooData的方法如下:
public Foo GetFooData()
{
var ds = _dataStore.GetDataBySP("sp name");
//is the below code breaking the DI pattern rule?
return ds.Tables[0].AsEnumberable().Select(f => new Foo(f)).FirstOrDefault();
}
在 Startup.cs 内的 ConfigureServices(IServiceCollection services) 方法中,我执行以下操作:
services.AddScoped<IFoo, Foo>();
所以我的问题是,通过在 Select() 中执行 new Foo(f) 是否打破了 DI 模式?如果是的话,请您建议如何克服这个问题。
【问题讨论】:
-
你应该问问自己
Foo-instance 是否真的应该创建其他实例。我怀疑它应该,而不是你可能有一个工厂来做这项工作。 -
@HimBromBeere 我在
Startup.cs中调用services.AddScoped<IFoo, Foo>()。你说的是工厂吗? -
这里没有 DI 开始。其次,由于某种原因,模式问题通常是题外话,最后,有很多教程和博客详细介绍了 DI 和 IOC,与 Q 和 A 格式相比,您将在那里获得更好的信息网站
-
这可能只是问题的表达方式,但看起来
Foo正在破坏 SRP - 单一责任原则。这让我想知道这是不是XY problem。 -
只需在 FooFactory 中移动 GetFooData 方法。这样就干净了。
标签: c# dependency-injection .net-core asp.net-core-mvc