/
AttributeBasedRegisterer.cs
86 lines (78 loc) · 2.46 KB
/
AttributeBasedRegisterer.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Reflection;
using Castle.Core;
using Castle.MicroKernel;
namespace Castle.Facilities.DeferredServiceResolution
{
public class AttributeBasedRegisterer
{
#region Logging
private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(AttributeBasedRegisterer));
#endregion
public void RegisterAssembly(IKernel kernel, Assembly assembly)
{
foreach (Type type in assembly.GetTypes())
{
if (HasAttribute(type))
{
RegisterType(kernel, type);
}
}
}
public void RegisterType(IKernel kernel, Type type)
{
if (type.IsAbstract || type.IsInterface)
{
throw new InvalidOperationException("Can't register abstract type: " + type);
}
if (!kernel.HasComponent(type) && !IsManualRegistered(type))
{
WindsorServiceAttribute details = GetWindsorServiceAttribute(type);
string key = CreateKey(type);
if (details != null && !String.IsNullOrEmpty(details.Name))
{
key = details.Name;
}
if (details != null && details.ServiceType != null)
{
_log.DebugFormat("Registering {0} as {1} providing {2}", type, key, details.ServiceType);
kernel.AddComponent(key, details.ServiceType, type);
}
else
{
_log.DebugFormat("Registering {0} as {1}", type, key);
kernel.AddComponent(key, type);
}
}
}
private static bool IsManualRegistered(Type type)
{
return AttributeHelper.GetSingleUseAttribute<ManualWindsorRegistrationAttribute>(type) != null;
}
private static bool HasAttribute(Type type)
{
return AttributeHelper.GetSingleUseAttribute<LifestyleAttribute>(type) != null;
}
private static WindsorServiceAttribute GetWindsorServiceAttribute(Type type)
{
return AttributeHelper.GetSingleUseAttribute<WindsorServiceAttribute>(type);
}
private static string CreateKey(Type serviceType)
{
return serviceType.FullName;
}
}
public static class AttributeHelper
{
public static T GetSingleUseAttribute<T>(Type type) where T : Attribute
{
T[] attributes = (T[]) type.GetCustomAttributes(typeof(T), true);
if (attributes.Length == 0)
{
return null;
}
return attributes[0];
}
}
}