使用Autofac进行间接参数化实例化

时间:2017-01-24 11:56:59

标签: autofac

我正在 ethnicGroup: AbstractControl; form: FormGroup; type: AbstractControl; constructor( private _fb: FormBuilder) { this.form = this._fb.group( { 'type': [ '', ], 'ethnicGroup': [ '', ] } ); this.type = this.form.controls[ 'type' ]; this.ethnicGroup = this.form.controls[ 'ethnicGroup' ] } 尝试使用Autofac的parameterized instantiation解析间接依赖关系。

假设我有以下类:

DependencyResolutionException

现在假设我想要public interface IMuffin {} public class Muffin : IMuffin { public Muffin(IButter butter) {} } public interface IButter {} public class Butter : IButter { public Butter(IKnife knife) {} } public interface IKnife {} ,但我想提供IMuffin依赖项作为参数,如下所示:

IKnife

问题是,我在public class Breakfast { public Breakfast(Func<IKnife, IMuffin> muffinFactory) { var muffin = muffinFactory(new Knife()); } private class Knife : IKnife {} } 抱怨工厂无法使用可用参数和服务来解析muffinFactory(new Knife())构造函数的IKnife依赖关系时遇到异常。这没有任何意义,因为我提供了Butter的实例作为工厂的参数。

这似乎应该有效。我错过了什么?

1 个答案:

答案 0 :(得分:0)

您示例中的工厂是IMuffin的工厂,您的IKnife参数传递为typed parameter。但是,您的Muffin课程不需要IKnife个实例。它需要一个IButter实例。

IKnife类需要Butter个实例。但是,传递给工厂的参数只能用于创建Muffin实例,并且不用于解析Muffin的依赖关系。 muffinFactory的正确类型为Func<IButter, IMuffin>

要使您的示例正常工作,您需要两个工厂:

public class Breakfast
{
   public Breakfast(Func<IKnife, IButter> butterFactory, Func<IButter, IMuffin> muffinFactory)
   {
      var butter = butterFactory(new Knife());
      var muffin = muffinFactory(butter);
   }

   private class Knife : IKnife { }
}
相关问题