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.
15 namespace Castle
.MicroKernel
.Registration
20 /// Describes how to select a types service.
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
;
35 /// Uses the base type matched on.
37 /// <returns></returns>
38 public TypesDescriptor
Base()
40 return Select(delegate { return typesDescriptor.BasedOn; }
);
44 /// Uses the first interface of a type.
46 /// <returns></returns>
47 public TypesDescriptor
FirstInterface()
49 return Select(delegate(Type type
)
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();
70 /// Assigns a custom service selection strategy.
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
;