【问题标题】:passing optional parameter to autofac将可选参数传递给 autofac
【发布时间】:2012-11-08 15:26:45
【问题描述】:

我正在尝试使用 Autofac 并注册下面的类,该类接收参数之一作为可选参数(或者更确切地说是 null)。 我的课程是:

class BaseSpanRecord : ISpanRecord
{
    public BaseSpanRecord(RecordType recordType, List<SpanRecordAttribute> properties)
    {
        RecordType = recordType;
        Properties = properties;
    }
}

这里 RecordType 是一个枚举,而 SpanRecordAttribute 是一个只有属性的类,我不想为其创建任何接口。

构造函数中RecordTypeProperties是接口ISpanRecord的两个公共属性 这个类可以在程序的不同地方通过以下方式实例化:

ISpanRecord spanFileRecord = new BaseSpanRecord(recordType, null);

ISpanRecord spanFileRecord = new BaseSpanRecord(recordType, recordAttributeList);

我应该如何尝试在 Autofac 容器中注册它以便它可以处理上述两种情况? 或者我应该改变 BaseSpanRecord 类的编写方式以使其注册更容易?

【问题讨论】:

  • 我尝试使用以下方法:builder.RegisterType&lt;BaseSpanRecord&gt;().UsingConstructor(typeof(RecordType), typeof(List&lt;SpanRecordAttribute&gt;)).As&lt;ISpanRecord&gt;().InstancePerDependency(); 但是它不适用于第一种情况。

标签: c# autofac


【解决方案1】:

当使用TypeParameter 解析实例时,只要提供null 的类型信息就可以了。您不需要在注册时使用UsingConstructor 方法。

直接创建 TypedParameter 实例:

var recordTypeParam = new TypedParameter(typeof(RecordType), RecordType.Something);
var propertiesParam = new TypedParameter(typeof(List<SpanRecordAttribute>), null);
var record = container.Resolve<ISpanRecord>(recordTypeParam, propertiesParam);

使用TypedParameter.From 辅助方法:

var record = container.Resolve<ISpanRecord>(TypedParameter.From(RecordType.Something), TypedParameter.From((List<SpanRecordAttribute>)null));

请注意,null 被强制转换为 List&lt;SpanRecordAttribute&gt; 以允许使用辅助方法进行类型推断。

【讨论】:

  • 谢谢@Alex。它解决了我的问题。但现在有几个问题。我什么时候应该使用UsingConstructor()WithParameter()builder.Register(c=&gt; new ClassA(c.Resolve&lt;ClassB&gt;())) 当autofac 可以解析构造函数参数而无需在注册时指定它们。请原谅我对 Autofac 的了解,因为我无法理解 Autofac wiki 中所写的大部分内容。我正在寻找相同的可能场景。如果您可以提供任何链接或书籍等,那将非常有帮助。
猜你喜欢
  • 2011-08-10
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多