Kai*_*Kai 14 c# dependency-injection
目前我正在尝试使用依赖注入容器,这次使用Unity.
给出以下界面:
public interface IPodcastCommService
{
void Download();
void Upload();
}
Run Code Online (Sandbox Code Playgroud)
以及以下实施:
public class PodcastService
{
private IPodcastCommService commservice;
private String url;
public PodcastService(String url, IPodcastCommService commservice)
{
this.commservice = commservice;
this.url = url;
}
}
Run Code Online (Sandbox Code Playgroud)
由于构造函数,我一直在寻找一个解决方案来将参数传递给它并找到它:
var p = container.Resolve<IPodcastCommService>(new ParameterOverride("url", myUrl));
Run Code Online (Sandbox Code Playgroud)
到目前为止一切都那么好,但与此同时我读到了这是多么糟糕,这个类的设计有多糟糕,是的,它看起来有点难看.但是如何以优雅的方式将参数传递给类?
我的第一个想法是将它作为一个属性来做,但是每次我需要它已经给出的Url时我必须检查.
更新: 一个例子,我读到这是一个糟糕的设计,是这样的:
但是在某些情况下,您可以为解析操作传递自定义构造函数参数.有些人可能会争辩说,这种糟糕的体系结构的尖叫声,但有一些情况,比如将DI容器带到遗留系统,可能需要这些操作.
资料来源:http://mikaelkoskinen.net/unity-passing-constructor-parameters-to-resolve/
我不明白为什么你需要 PodcastService 的组合IPodcastCommService,而不是实现IPodcastCommService并通过字符串注入 url。我不明白为什么你的设计不好。恕我直言,注入 url 很好。
如果您想到更好的方法,我认为可以通过注入上下文/配置而不是本机数据类型来替换它。
public class PodcastService
{
private IPodcastCommService commservice;
private IConnectionContext connection;
public PodcastService(IConnectionContext connection, IPodcastCommService commservice)
{
this.commservice = commservice;
this.connection= connection;
}
}
public interface IConnectionContext{
string PodcastServiceUrl{get;}
}
Run Code Online (Sandbox Code Playgroud)
但同样,我没有发现常规方法有任何好处(除非您可以处理会话/常量/静态字段)。
更新:
我在这里发现了关于糟糕设计的类似问题。总而言之,并不是原生类型参数(字符串等)或自定义构造函数参数不好。只是你需要将参数放到真正负责该参数的类中。如果您在抽象工厂模式中处理 if-else 条件,则需要自定义构造函数参数。