ReflectionActivator 在其私有字段中包含配置参数和配置属性。您可以通过反射阅读它们
var configuredParameters = (IEnumerable<Parameter>)typeof(ReflectionActivator).GetField("_configuredParameters", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(reflectionActivator);
var configuredProperties = (IEnumerable<Parameter>)typeof(ReflectionActivator).GetField("_configuredProperties", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(reflectionActivator);
还有一个工作示例:
class Program
{
interface IInterface
{
}
class MyClass : IInterface
{
private readonly string _name;
public MyClass(string name)
{
_name = name;
}
protected MyClass()
{
}
public override string ToString()
{
return string.Format("{0} {1}", GetType(), _name);
}
}
class MyReplacementClass : MyClass
{
private readonly string _name;
public MyReplacementClass(string name)
{
_name = name;
}
public override string ToString()
{
return string.Format("{0} {1}", GetType(), _name);
}
}
class MyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<MyClass>().As<IInterface>().WithParameter("name", "Parameter");
}
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry,
IComponentRegistration registration)
{
var reflectionActivator = ((ComponentRegistration) registration).Activator as ReflectionActivator;
if (reflectionActivator == null)
return;
var replacementType = ReplaceType(reflectionActivator.LimitType);
if (replacementType == reflectionActivator.LimitType)
return;
var configuredParameters = (IEnumerable<Parameter>)typeof(ReflectionActivator).GetField("_configuredParameters",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(reflectionActivator);
var configuredProperties = (IEnumerable<Parameter>)typeof(ReflectionActivator).GetField("_configuredProperties",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(reflectionActivator);
((ComponentRegistration) registration).Activator = new ReflectionActivator(
replacementType,
reflectionActivator.ConstructorFinder,
reflectionActivator.ConstructorSelector,
configuredParameters,
configuredProperties
);
}
private Type ReplaceType(Type limitType)
{
return typeof (MyReplacementClass);
}
}
static void Main(string[] args)
{
var builer = new ContainerBuilder();
builer.RegisterModule<MyModule>();
using (var container = builer.Build())
{
var myClass = container.Resolve<IInterface>();
Console.WriteLine(myClass);
Console.ReadKey();
}
}
}