根据之前的回答,我想到了创建一个TypeConverter来访问任何静态属性的想法。以下是我的实现:
TypeConverter 实现
using System;
using System.ComponentModel;
using System.Reflection;
namespace EntLibUnity.Extensions
{
public class StringToStaticInstanceTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return (typeof(string) == sourceType) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string stringValue;
if (value == null
|| (stringValue = value as string) == null
|| string.IsNullOrEmpty(stringValue)
|| !stringValue.Contains("@")
)
{
return null;
}
var stringParts = stringValue.Split('@');
if (stringParts.Length != 2)
{
return null;
}
var staticProperty = stringParts[0];
var assemblyQualifiedName = stringParts[1];
var staticClassType = Type.GetType(assemblyQualifiedName, true);
var staticPropertyInfo = staticClassType.GetProperty(staticProperty,
BindingFlags.Public | BindingFlags.Static |
BindingFlags.FlattenHierarchy);
var staticValue = staticPropertyInfo.GetValue(null, null) ?? base.ConvertFrom(context, culture, value);
return staticValue;
}
}
}
一个使用的例子:
假设以下接口和具体实现:
namespace EntLibUnity.UnitySample
{
public class VersionManager : IVersionManager
{
private readonly Version _version;
public string Version
{
get { return _version.ToString(); }
}
public VersionManager(Version version)
{
_version = version;
}
}
}
namespace EntLibUnity.Infrastructure
{
public interface IVersionManager
{
string Version { get; }
}
}
我们的具体版本依赖于System.Version,因此我们配置容器来提供这个值。在我的例子中,我将使用配置文件来实现这个目的。
<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="StringToStaticInstanceTypeConverter" type="EntLibUnity.Extensions.StringToStaticInstanceTypeConverter, EntLibUnity.Extensions" />
<alias alias="IVersionManager" type="EntLibUnity.Infrastructure.IVersionManager, EntLibUnity.Infrastructure" />
<alias alias="VersionManager" type="EntLibUnity.UnitySample.VersionManager, EntLibUnity.UnitySample" />
<container>
<register type="IVersionManager" mapTo="VersionManager">
<constructor>
<param name="version">
<value value="Version@System.Environment, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" typeConverter="StringToStaticInstanceTypeConverter" />
</param>
</constructor>
</register>
</container>
</unity>
最后,一旦加载了配置,您可以按以下方式使用:
var versionManager = container.Resolve<IVersionManager>()
Console.WriteLine(versionManager.Version)
祝你好运