具有默认参数的Unity构造函数

时间:2014-11-29 16:54:44

标签: c# unity-container code-injection

使用默认参数注入构造函数时出现问题。

例如

container.RegisterType<IAddressImportRepository, AddressImportRepository>(
    new PerRequestLifetimeManager());

public AddressImportRepository(
    FairFlexxDbContext context, bool isUseSecurePredicate = true)
    : base(context, isUseSecurePredicate)
{
}

错误:

  

[InvalidOperationException:布尔类型没有   可访问的构造函数。]
  Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext   上下文)+239 lambda_method(Closure,IBuilderContext)+60
  Microsoft.Practices.ObjectBuilder2&LT;&GT; c__DisplayClass1.b__0(IBuilderContext   上下文)+71
  Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext   上下文)+42
  Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext   上下文)+333
  Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext   上下文)+274
  Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey   newBuildKey)+167
  Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext   上下文)+101 lambda_method(Closure,IBuilderContext)+425
  Microsoft.Practices.ObjectBuilder2&LT;&GT; c__DisplayClass1.b__0(IBuilderContext   上下文)+71
  Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext   上下文)+42
  Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext   上下文)+333
  Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext   上下文)+274
  Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey   newBuildKey)+167
  Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext   上下文)+101 lambda_method(Closure,IBuilderContext)+222
  Microsoft.Practices.ObjectBuilder2&LT;&GT; c__DisplayClass1.b__0(IBuilderContext   上下文)+71
  Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext   上下文)+42
  Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext   上下文)+333
  Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext   上下文)+274
  Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t,Object   existing,String name,IEnumerable`1 resolverOverrides)+383

1 个答案:

答案 0 :(得分:9)

Unity使用反射来确定构造函数参数类型。使用构造函数,它找到了参数FairFlexxDbContext和bool。它试图构造每种类型的实例并在bool上失败,因为它是一个值类型。它无法识别您提供的默认值以通过此错误。

要实现这一点,您有几个选择。要么使用InjectionConstructor告诉注册表IAddressImportRepository并告诉 如何解析构造函数参数,要么将bool参数移动为属性。由于bool是一个可选参数,我建议将其移动为属性。

container.RegisterType<IAddressImportRepository, AddressImportRepository>(
    new PerRequestLifetimeManager(), 
    new InjectionConstructor(new ResolvedParameter<FairFlexxDbContext>(), true));

public AddressImportRepository(FairFlexxDbContext context)
    : base(context, true)
{
    IsUseSecurePredicate = true;
}

public bool IsUseSecurePredicate { get; set; }