将可选参数传递给autofac [英] passing optional parameter to autofac

查看:88
本文介绍了将可选参数传递给autofac的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use Autofac and register the below class which receives one of the parameter as optional parameter (or rather null). My classes are:

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

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

Here RecordType is an enum and SpanRecordAttribute is a class with only properties for which i don't want to create any interface.

在构造函数 RecordType Properties 中,它们是接口 ISpanRecord 的两个公共属性. 可以通过以下方式在程序中的不同位置实例化该类:

In the constructor RecordType and Properties are the two public properties of the interface ISpanRecord This class can be instantiated in the following ways in different places in the program:

ISpanRecord spanFileRecord = new BaseSpanRecord(recordType, null);

ISpanRecord spanFileRecord = new BaseSpanRecord(recordType, recordAttributeList);

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

How should i try to register this in the Autofac container so that it can handle the above two cases? Or should i change something in the way BaseSpanRecord class has been written to make its registration easier?

推荐答案

使用TypeParameter解析实例时,只要提供类型信息null应该很好.您不需要在注册时使用UsingConstructor方法.

When using a TypeParameter to resolve the instance as long as you provide the type information null should be fine. You should not need to use the UsingConstructor method on your registration.

直接创建TypedParameter实例:

Creating TypedParameter instances directly:

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<SpanRecordAttribute>,以允许使用辅助方法进行类型推断.

Notice that the null was cast to List<SpanRecordAttribute> to allow for type inference with the helper method.

这篇关于将可选参数传递给autofac的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆