-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPropertyInjector.cs
49 lines (42 loc) · 1.53 KB
/
PropertyInjector.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;
using Autofac;
using Autofac.Core;
namespace ContinuousRunner
{
public static class PropertyInjector
{
public static void InjectProperties(IComponentContext context, object instance)
{
var properties = instance.GetType().GetFields(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var fieldInfo in properties)
{
var propertyType = fieldInfo.FieldType;
if (propertyType.IsValueType || !context.IsRegistered(propertyType))
{
continue;
}
if (HasImportAttribute(fieldInfo))
{
if (fieldInfo.GetValue(instance) != null)
{
continue; // do not overwrite existing non-null values
}
var obj = context.Resolve(propertyType);
if (obj == null)
{
throw new DependencyResolutionException(
$"Unable to resolve dependency import on {instance.GetType()} -> {fieldInfo}");
}
fieldInfo.SetValue(instance, obj);
}
}
}
private static bool HasImportAttribute(MemberInfo propertyInfo)
{
return propertyInfo.GetCustomAttributes(typeof(ImportAttribute)).Any();
}
}
}