是否IoC容器更换使用的工厂 [英] Does an IoC container replace the use of Factories
问题描述
我刚开始使用IoC容器中,所以道歉,如果这是一个愚蠢的问题。
I am just getting started with IoC containers so apologies if this is a stupid question.
我有这样的一个应用程序
I have code like the following in an app
internal static class StaticDataHandlerFactory
{
public static IStaticDataHandler CreateHandler(StaticDataUpdate staticDataUpdate)
{
if (staticDataUpdate.Item is StaticDataUpdateOffice)
{
return new OfficeUpdateHandler();
}
if (staticDataUpdate.Item is StaticDataUpdateEmployee)
{
return new EmployeeUpdateHandler();
}
if (staticDataUpdate.Item == null)
{
throw new NotImplementedException(
string.Format("No static data provided"));
}
else
{
throw new NotImplementedException(
string.Format("Unimplemented static data type of {0}", staticDataUpdate.Item.GetType().FullName));
}
}
}
它基本上是一个简单的工厂返回用于处理输入数据的正确策略。
It is basically a simple factory that returns the correct strategy for handling the input data.
会IoC容器允许我以消除这样的代码?这就是说:?那就让我来动态地选择一个具体的实现,以基于负载的输入参数的类型
Would an IoC container allow me to eliminate code like this? That is to say : would it allow me to dynamically choose a concrete implementation to load based on the type of an input parameter?
还是我的路要走当然这里
Or am I way off course here?
推荐答案
事实上,尽管有可能与控制系统的反转,以取代一些代码,这不是明显对我来说这是一个好主意。依赖注入往往是最适合的系统配置,而不是动态创建的对象。把它用不同的方式,容器本身是一个巨大的全局变量,因此应该出现在很多你的代码。
Actually, although it is possible to replace some of the code with an inversion of control system, it's not obvious to me it's a good idea. Dependency injection tends to be best for configuration of systems, not dynamic creation of objects. To put it a different way, the container itself is a huge global variable and as such should appear in much of your code.
顺便说一句,该代码似乎是违反德米特法。看来,参数应该是类型StaticDataUpdateItem而不是StaticDataUpdate。与观察到的,还有重写此代码对StaticDataUpdateItem一个方法调用一个非常有力的论据。
As an aside, the code appears to be violating the Law of Demeter. It appears that the parameter should be of type "StaticDataUpdateItem" rather than "StaticDataUpdate". With that observed, there's a pretty strong argument for rewriting this code as a method call on the StaticDataUpdateItem.
我用的IoC相当严重,但动态对象创建犹未处理用抽象工厂模式。总之,如果你不喜欢添加一个方法,以项目本身来生成手柄的想法,代码可能是最好离开它是这样的。
I used IoC quite heavily, but dynamic object creation is still better dealt with using an abstract factory pattern. In short, if you don't like the idea of adding a method to the item itself to generate the handle, the code's probably best left the way it is.
这篇关于是否IoC容器更换使用的工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!