Removed untyped contructor from ComponentRegistration and add a protected setter.
[castle.git] / InversionOfControl / Castle.MicroKernel / SubSystems / Conversion / Converters / AttributeAwareConverter.cs
blob440d5570dd38dbb242bbe0b7411c17998a62bea6
1 // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
2 //
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
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
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
17 using System;
18 using Castle.MicroKernel.SubSystems.Conversion;
20 /// <summary>
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.
23 /// </summary>
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);
36 else
38 return false;
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);
54 #endregion
56 private ITypeConverter TryGetConverterInstance(Type type)
58 ITypeConverter converter = null;
60 ConvertibleAttribute attr = (ConvertibleAttribute)
61 Attribute.GetCustomAttribute(type, typeof(ConvertibleAttribute));
63 if (attr != null)
65 converter = (ITypeConverter) Activator.CreateInstance(attr.ConverterType);
66 converter.Context = Context;
69 return converter;
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.");
81 return converter;