StructureMap打开具有多种类型

时间:2017-09-18 12:20:28

标签: c# inversion-of-control ioc-container structuremap

所以我一直试图解决这个问题几个小时了。我搜索了互联网并查看了许多Stackoverflow问题,但没有人可以帮助我。

所以我正在构建一个管道。基本的conecpt如下:

  • PipelineStore(Singleton) - 包含所有已注册的Pipeline
  • 管道[TEntity](瞬态) - 每个实体一个Pipeline(帐户,联系人,......)
  • PipelineStep [TOperation,TInteractor,TEntity](瞬态) - 每Pipeline个多步骤

[]代表泛型类型。

我想使用StructureMap来创建Pipeline和PipelineStep。所以我创建了一个名为IPipelineFactory的汽车工厂,它有一个功能:

IPipeline<TEntity> CreatePipeline<TEntity>() TEntity : EntityDTO, new();

我在注册表中注册了它:

For<IPipelineFactory>().CreateFactory();
For(typeof(IPipeline<>))
    .Use(typeof(Pipeline<>))
    .Transient();

然后我注入了IPipelineFactory并使用它如下:

public IPipeline<TEntity> NewPipeline<TEntity>() 
    where TEntity : EntityDTO, new()
{
    var pipeline = _pipelineFactory.CreatePipeline<TEntity>();
    _pipelines.Add(pipeline);
    return pipeline;
}

这很好用,但是当我尝试使用PipelineStep做同样的事情时它会失败:

public interface IPipelineStepFactory
{
    IPipelineStep<TOperation, TInteractor, TEntity> CreatePipelineStep<TOperation, TInteractor, TEntity>() 
        where TOperation : IOperation<TInteractor, TEntity> 
        where TInteractor : IInteractor<TEntity>
        where TEntity : EntityDTO, new();
}

注册:

For<IPipelineStepFactory>().CreateFactory();
For(typeof(IPipelineStep<,,>))
    .Use(typeof(PipelineStep<,,>));

用法:

public IAddPipeline<TEntity> Pipe<TOperation, TInteractor>()
    where TOperation : IOperation<TInteractor, TEntity>
    where TInteractor : IInteractor<TEntity>
{
    var step = PipelineStepFactory.CreatePipelineStep<TOperation, TInteractor, TEntity>();
    RegisteredSteps.Add(step);
    return this;
}

当我尝试测试代码时,它会在运行时抛出以下异常:

No default Instance is registered and cannot be automatically determined for type 'IPipelineStep<TestOperation, ITestInteractor, TestEntity>'

There is no configuration specified for IPipelineStep<TestOperation, ITestInteractor, TestEntity>

我认为它可能缺少对具有多个类型参数的开放泛型类型的支持。如果有解决此问题的任何工作方法,请告诉我。谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

所以我自己弄清楚了。问题是,PipelineStep的泛型类型约束略有不同导致了这个问题。我改变了

public class PipelineStep<TOperation, TInteractor, TEntity> : PipelineStepBase, IPipelineStep<TOperation, TInteractor, TEntity> 
    where TOperation : IOperation<TInteractor, TEntity>, IOperation<IInteractor<EntityDTO>, EntityDTO>
    where TInteractor : IInteractor<TEntity>, IInteractor<EntityDTO>
    where TEntity : EntityDTO

public class PipelineStep<TOperation, TInteractor, TEntity> : PipelineStepBase, IPipelineStep<TOperation, TInteractor, TEntity> 
        where TOperation : IOperation<TInteractor, TEntity>
        where TInteractor : IInteractor<TEntity>
        where TEntity : EntityDTO

现在它正在工作!