passing optional parameter to autofac

Deadly 提交于 2019-12-08 13:44:50

问题


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;
    }
}

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

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);

or

ISpanRecord spanFileRecord = new BaseSpanRecord(recordType, recordAttributeList);

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?


回答1:


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.

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);

Using the TypedParameter.From helper method:

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

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



来源:https://stackoverflow.com/questions/13274547/passing-optional-parameter-to-autofac

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!