1 // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.using System;
15 namespace Castle
.MicroKernel
.SubSystems
.Conversion
18 using Castle
.MicroKernel
.SubSystems
.Conversion
;
21 /// Looks for a <see cref="ConvertibleAttribute"/> on the type to be converted.
22 /// If found, the TypeConverter defined by the attribute is used to perform the conversion.
24 public class AttributeAwareConverter
: AbstractTypeConverter
26 #region ITypeConverter Member
28 public override bool CanHandleType(Type type
)
30 ITypeConverter converter
= TryGetConverterInstance(type
);
32 if (converter
!= null)
34 return converter
.CanHandleType(type
);
42 public override object PerformConversion(string value, Type targetType
)
44 ITypeConverter converter
= GetConverterInstance(targetType
);
45 return converter
.PerformConversion(value, targetType
);
48 public override object PerformConversion(Castle
.Core
.Configuration
.IConfiguration configuration
, Type targetType
)
50 ITypeConverter converter
= GetConverterInstance(targetType
);
51 return converter
.PerformConversion(configuration
, targetType
);
56 private ITypeConverter
TryGetConverterInstance(Type type
)
58 ITypeConverter converter
= null;
60 ConvertibleAttribute attr
= (ConvertibleAttribute
)
61 Attribute
.GetCustomAttribute(type
, typeof(ConvertibleAttribute
));
65 converter
= (ITypeConverter
) Activator
.CreateInstance(attr
.ConverterType
);
66 converter
.Context
= Context
;
72 private ITypeConverter
GetConverterInstance(Type type
)
74 ITypeConverter converter
= TryGetConverterInstance(type
);
76 if (converter
== null)
78 throw new InvalidOperationException("Type " + type
.Name
+ " does not have a Convertible attribute.");