Fixing an issue with output parameters that are of type IntPtr
[castle.git] / InversionOfControl / Castle.MicroKernel / Registration / Strategies / ServiceDescriptor.cs
blobb9d8693c57f9da31cedf963ebeedf9137a3db965
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.
15 namespace Castle.MicroKernel.Registration
17 using System;
19 /// <summary>
20 /// Describes how to select a types service.
21 /// </summary>
22 public class ServiceDescriptor
24 public delegate Type ServiceSelector(Type type);
26 private readonly TypesDescriptor typesDescriptor;
27 private ServiceSelector serviceSelector;
29 internal ServiceDescriptor(TypesDescriptor typesDescriptor)
31 this.typesDescriptor = typesDescriptor;
34 /// <summary>
35 /// Uses the base type matched on.
36 /// </summary>
37 /// <returns></returns>
38 public TypesDescriptor Base()
40 return Select(delegate { return typesDescriptor.BasedOn; });
43 /// <summary>
44 /// Uses the first interface of a type.
45 /// </summary>
46 /// <returns></returns>
47 public TypesDescriptor FirstInterface()
49 return Select(delegate(Type type)
51 Type first = null;
52 Type[] interfaces = type.GetInterfaces();
53 if (interfaces.Length > 0)
55 first = interfaces[0];
57 // This is a workaround for a CLR bug in
58 // which GetInterfaces() returns interfaces
59 // with no implementations.
60 if (first.IsGenericType && first.ReflectedType == null)
62 first = first.GetGenericTypeDefinition();
65 return first;
66 });
69 /// <summary>
70 /// Assigns a custom service selection strategy.
71 /// </summary>
72 /// <param name="selector"></param>
73 /// <returns></returns>
74 public TypesDescriptor Select(ServiceSelector selector)
76 serviceSelector = selector;
77 return typesDescriptor;
80 internal Type GetService(Type type)
82 if (serviceSelector != null)
84 return serviceSelector(type) ?? type;
86 return type;