d45*_*453 26 .net c# decoupling
我在"自适应代码通过C#"一书中遇到了"Stairway"模式描述,我真的不明白这是如何实现的:
(来源)
所以我有客户端组装:
using ServiceInterface;
namespace Client
{
class Program
{
static void Main(string[] args)
{
// Have to create service implementation somehow
// Where does ServiceFactory belong?
ServiceFactory serviceFactory = new ServiceFactory();
IService service = serviceFactory.CreateService();
service.Do();
}
}
}
Run Code Online (Sandbox Code Playgroud)
服务接口组件:
namespace Service
{
public interface IService
{
void Do();
}
}
Run Code Online (Sandbox Code Playgroud)
和服务实现程序集:
using ServiceInterface;
namespace ServiceImplementation
{
public class PrintService : IService
{
public void Do()
{
Console.WriteLine("Some work done");
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:如何IService
在Client
命名空间中获取对象?我应该在哪里放置实际的new PrintService()
物体?这不能成为其中的一部分ServiceInterface
,因为接口组件不依赖于ServiceImplementation
.但它也不能成为一部分Client
或ServiceImplementation
因为Client
应该只依赖于它ServiceInterface
.
我来的唯一解决方案是有Application
在它的上面,它具有所有三个引用组件(Client
,ServiceInterface
和ServiceImplementation
),并注入IService
到Client
.我错过了什么吗?
Gar*_*all 20
应用入口点应该是组合根,根据Mark Seemann出版的关于依赖注入的优秀书籍.在这里,问题更多的是关于依赖性倒置,客户端和实现都应该依赖于抽象.
该图未显示的内容,但希望本书的其他部分明确指出,入口点自然而且必然会引用构建任何解析根(控制器,服务等)所需的一切.但这是在只拥有这样的知识的地方.
请记住,客户有时可以"拥有"它们所依赖的接口:接口ISecurityService
可能存在于Controllers
程序集中,IUserRepository
可能存在于ServiceImplementations
程序集中,等等.当然,当> 1客户端需要访问接口时,这是不切实际的.
如果您遵循SOLID,您自然会发现依赖注入是必需的,但控制反转容器不是优先考虑的事情.我发现自己越来越多地使用Pure Dependency Injection(手动构建解析根).