Added container accessor to Castle.Core
[castle.git] / InversionOfControl / Castle.MicroKernel / Facilities / FactorySupport / AccessorActivator.cs
blob897e0ba4cef88121bc15d9e96100706be0102fa8
1 // Copyright 2004-2007 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.Facilities.FactorySupport
17 using System;
18 using System.Reflection;
20 using Castle.Core;
21 using Castle.MicroKernel;
22 using Castle.MicroKernel.ComponentActivator;
23 using Castle.MicroKernel.Facilities;
26 public class AccessorActivator : DefaultComponentActivator
28 public AccessorActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction) : base(model, kernel, onCreation, onDestruction)
32 protected override object Instantiate(CreationContext context)
34 String accessor = (String) Model.ExtendedProperties["instance.accessor"];
36 PropertyInfo pi = Model.Implementation.GetProperty(
37 accessor, BindingFlags.Public|BindingFlags.Static );
39 if (pi == null)
41 String message = String.Format("You have specified an instance accessor " +
42 "for the component '{0}' {1} which could not be found (no public " +
43 "static property has this name)", Model.Name, Model.Implementation.FullName);
44 throw new FacilityException(message);
47 if (!pi.CanRead)
49 String message = String.Format("You have specified an instance accessor " +
50 "for the component '{0}' {1} which is write-only",
51 Model.Name, Model.Implementation.FullName);
52 throw new FacilityException(message);
55 try
57 return pi.GetValue( null, new object[0] );
59 catch(Exception ex)
61 String message = String.Format("The instance accessor " +
62 "invocation failed for '{0}' {1}",
63 Model.Name, Model.Implementation.FullName);
64 throw new FacilityException(message, ex);