问题
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