本文介绍了IoC:如何动态创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在需要动态创建对象的情况下,我很难理解如何使用IoC.假设我有这个课程:

I have a problem to understand how to use IoC in a scenario where I need to create objects dynamically. Lets assume I have this classes:

abstract class Field {
  public Field( ICommandStack commandStack ) {}
}

abstract class Entity {
  public readonly Collection<Field> Fields { get; }
}

class EntityA {
  public EntityA( ICommandStack commandStack ) {
    Fields.Add( new StringField( commandStack ) );
  }
}

class EntitiyB {
  public EntityB( ICommandStack commandStack ) {
    Fields.Add( new IntField( commandStack ) );
    Fields.Add( new IntField( commandStack ) );
    Fields.Add( new IntField( commandStack ) );
  }
}

所以我的问题是在构造函数中创建字段.我的字段需要ICommandStack,但实体则不需要.他们仅获得ICommandStack来创建其字段.

So my problem is the creation of Fields in the constructors. My Fields need an ICommandStack, but the Entities do not. They only get the ICommandStack for the creation of their Fields.

在每个实体的构造函数中请求字段作为参数可能会更容易.但是单个实体的字段数可能大于10.我不想创建具有这么多参数的构造函数.

It could be easier to request the Fields as an argument in each Entity's constructor. But the number of Fields could be >10 for single Entities. I don't want to create constructors with so many parameters.

所以我的想法是将FieldFactory移交给实体:

So my idea was to hand over a FieldFactory to the Entites:

class EntityA {
  public EntityA( IFieldFactory fieldFactory ) {
    // create as many fields as needed via the factory
    Fields.Add( fieldFactory.CreateStringField() );
  }
}

至少(对于实体)不必要的ICommandStack现在消失了.但是,FieldFactory如何创建一个Field?它只能获得ICommandStack的注入-但是仍然必须通过'new'关键字来完成Fields的创建.还是我应该给工厂提供有关我的DI容器的参考?

At least the (for Entity) unneccessary ICommandStack is now gone. But how does the FieldFactory create a Field? It only can get the ICommandStack injected - but the creation of Fields has still to be done via the 'new' keyword. Or should I give the factory a reference to my DI-container?

这里有什么好的设计解决方案?

What is a good design solution here?

推荐答案

我将使用FieldFactory并使用对容器(或对容器进行抽象的接口的引用来注入工厂,如果您不愿意采用强壮的容器依赖于您的容器).

I'd use a FieldFactory and inject the factory with a reference to the container (or to an interface that abstracts it if you are not happy with taking a strong dependency on your container).

否则,它一直是乌龟.您需要某个对象在某个时候向容器询问新实例.如果要对字段进行DI注入,则需要让容器来构建它们.

Otherwise, it's turtles all the way down. You need some object to ask the container for a new instance at some point. If you want your fields to be DI-injected, then you need to ask the container to build them or you.

总而言之,我会和工厂一起去.

So to summarize, I'd go with the factory.

这篇关于IoC:如何动态创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:10