IOC / DI:正在注册一个具体类型代码味道? [英] IOC/DI: Is Registering a Concrete Type a Code Smell?

查看:116
本文介绍了IOC / DI:正在注册一个具体类型代码味道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为此而努力对我当前的项目了一下。我已经遇到某些情况下,我有一个具体的类型不(且不需要)实现任何特定的接口。有时候我想,因为该类型与singleon生命周期注册决议通过容器发生;有时类型有是一个大的对象图的一部分,或者是自己与单身的生命周期注册的构造函数的参数。

I've been struggling with this a bit on my current project. I've come across some cases where I have a concrete type that does not (and does not need) to implement any specific interface. Sometimes I want resolution to happen via the container because the type is registered with singleon lifecycle; sometimes the type has constructor parameters that are part of a larger object graph or are themselves registered with singleton lifecycles.

它总是让人觉得有些奇怪,我当我输入如下代码

It always feels a bit strange to me when I type code like:

Container.RegisterType<MyConcreteType, MyConcreteType>();



这是否是一个代码气味或违反最佳实践使用IoC容器有什么想法?

Any thoughts on whether this is a code smell or violates best practices for using an IOC container?

推荐答案

IoC容器是一个的控制反转的容器,而不是抽象的容器或接口实现集装箱。这是完全合法的类映射到自己与具有容器来管理他们的一生。

IoC container is an Inversion of Control container, not Abstraction Container or Interface to Implementation Container. It is perfectly legitimate to map classes to themselves and having the container manage their lifetime.

如果您的设计不要求使用接口,不要强迫他们。这样做的将是一个设计的气味,即不必要的复杂性。

If your design does not call for using interfaces, don't force them. Doing that would be a design smell, namely needless complexity.

我觉得IoC容器中,如类固醇工厂。并不是每一个工厂是一个的摘要的工厂(如单身)。因此,不是在IoC容器注册的每个已是抽象的映射实现。

I think of IoC containers as factories on steroids. Not every factory is an abstract factory (e.g. singletons). Hence not every registration in IoC container has to be an implementation to abstraction mapping.

这篇关于IOC / DI:正在注册一个具体类型代码味道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆