상속: System.MarshalByRefObject, ISubDependencyResolver
예제 #1
0
		protected override object Instantiate(CreationContext context)
		{
			String accessor = (String) Model.ExtendedProperties["instance.accessor"];

			PropertyInfo pi = Model.Implementation.GetProperty( 
				accessor, BindingFlags.Public|BindingFlags.Static );

			if (pi == null)
			{
				String message = String.Format("You have specified an instance accessor " + 
					"for the component '{0}' {1} which could not be found (no public " + 
					"static property has this name)", Model.Name, Model.Implementation.FullName);
				throw new FacilityException(message);
			}

			if (!pi.CanRead)
			{
				String message = String.Format("You have specified an instance accessor " + 
					"for the component '{0}' {1} which is write-only", 
					Model.Name, Model.Implementation.FullName);
				throw new FacilityException(message);
			}

			try
			{
				return pi.GetValue( null, new object[0] );
			}
			catch(Exception ex)
			{
				String message = String.Format("The instance accessor " + 
					"invocation failed for '{0}' {1}", 
					Model.Name, Model.Implementation.FullName);
				throw new FacilityException(message, ex);
			}
		}
예제 #2
0
 public object Resolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model,
     DependencyModel dependency)
 {
     if (dependency.TargetType == typeof (ISession))
         return SessionFactory.OpenSession();
     return SessionFactory.OpenStatelessSession();
 }
예제 #3
0
 public object Resolve(CreationContext context, ISubDependencyResolver parentResolver,
     ComponentModel model,
     DependencyModel dependency)
 {
     Type t = dependency.TargetType.GetGenericArguments()[0];
     return kernel.ResolveAll(t, null);
 }
        public override object Resolve(CreationContext context)
        {
            var current = HttpContext.Current;
            if (current == null)
                throw new InvalidOperationException("HttpContext.Current is null. PerHttpApplicationLifestyle can only be used in ASP.NET");

            var app = current.ApplicationInstance;
            var lifestyleModule = app.Modules
                .Cast<string>()
                .Select(k => app.Modules[k])
                .OfType<PerHttpApplicationLifestyleModule>()
                .FirstOrDefault();
            if (lifestyleModule == null) {
                var message = string.Format("Looks like you forgot to register the http module {0}" +
                                               "\r\nAdd '<add name=\"PerHttpApplicationLifestyle\" type=\"{1}\" />' " +
                                               "to the <httpModules> section on your web.config",
                                               typeof (PerWebRequestLifestyleModule).FullName,
                                               typeof (PerWebRequestLifestyleModule).AssemblyQualifiedName);
                throw new ConfigurationErrorsException(message);
            }

            if (!lifestyleModule.HasComponent(PerAppObjectID)) {
                var instance = base.Resolve(context);
                lifestyleModule[PerAppObjectID] = instance;
                app.Disposed += (sender, args) => base.Release(instance);
            }

            return lifestyleModule[PerAppObjectID];
        }
예제 #5
0
		protected override object Instantiate(CreationContext context)
		{
			String factoryId = (String)Model.ExtendedProperties["factoryId"];
			String factoryCreate = (String)Model.ExtendedProperties["factoryCreate"];

			if (!Kernel.HasComponent(factoryId))
			{
				String message = String.Format("You have specified a factory ('{2}') " +
					"for the component '{0}' {1} but the kernel does not have this " +
					"factory registered",
					Model.Name, Model.Implementation.FullName, factoryId);
				throw new FacilityException(message);
			}

			IHandler factoryHandler = Kernel.GetHandler(factoryId);

			// Let's find out whether the create method is a static or instance method

			Type factoryType = factoryHandler.ComponentModel.Implementation;

			MethodInfo staticCreateMethod =
				factoryType.GetMethod(factoryCreate,
					BindingFlags.Public | BindingFlags.Static);

			if (staticCreateMethod != null)
			{
				return Create(null, factoryId, staticCreateMethod, factoryCreate, context);
			}
			else
			{
				object factoryInstance = Kernel[factoryId];

				MethodInfo instanceCreateMethod =
					factoryInstance.GetType().GetMethod(factoryCreate,
						BindingFlags.Public | BindingFlags.Instance);

				if (instanceCreateMethod == null)
				{
					factoryInstance = ProxyUtil.GetUnproxiedInstance(factoryInstance);

					instanceCreateMethod =
						factoryInstance.GetType().GetMethod(factoryCreate,
							BindingFlags.Public | BindingFlags.Instance);
				}

				if (instanceCreateMethod != null)
				{
					return Create(factoryInstance, factoryId, instanceCreateMethod, factoryCreate, context);
				}
				else
				{
					String message = String.Format("You have specified a factory " +
					                               "('{2}' - method to be called: {3}) " +
					                               "for the component '{0}' {1} but we couldn't find the creation method" +
					                               "(neither instance or static method with the name '{3}')",
					                               Model.Name, Model.Implementation.FullName, factoryId, factoryCreate);
					throw new FacilityException(message);
				}
			}
		}
		public object Resolve(CreationContext context,
		                      ISubDependencyResolver parentResolver,
		                      ComponentModel model,
		                      DependencyModel dependency)
		{
			return _kernel.ResolveAll(dependency.TargetType.GetElementType(), null);
		}
		public object Resolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model,
							  DependencyModel dependency)
		{
			Type elementType = dependency.TargetType.GetElementType();
			Array all = kernel.ResolveAll(elementType, new Hashtable());
			return all;
		}
        public override object Resolve(CreationContext context)
        {
            var store = GetStore();

            var instance = base.Resolve(context);

            if (instance == null)
            {
                if (context.Handler.ComponentModel.ExtendedProperties[Constants.REG_IS_INSTANCE_KEY] != null)
                {
                    throw new DependencyResolutionException("Cannot find the instance in the context store.");
                }
            }
            else if (store[Model.Name] == null)
            {
                store[Model.Name] = instance;
                store.GetContextInstances().Add(new ContextStoreDependency(Model.Name, instance, this));
                _isRegisteredForCleanup = true;
            }

            if (!_isRegisteredForCleanup)
            {
                store.GetContextInstances().Add(new ContextStoreDependency(Model.Name, instance, this));
                _isRegisteredForCleanup = true;
            }
            return store[Model.Name];
        }
예제 #9
0
		protected override object InternalCreate(CreationContext context)
		{
			String fileName = (String) Model.ExtendedProperties[IBatisNetFacility.MAPPER_CONFIG_FILE];
			bool isEmbedded = (bool) Model.ExtendedProperties[IBatisNetFacility.MAPPER_CONFIG_EMBEDDED];
			String connectionString = (String) Model.ExtendedProperties[IBatisNetFacility.MAPPER_CONFIG_CONNECTION_STRING];

			DomSqlMapBuilder domSqlMapBuilder = new DomSqlMapBuilder();
			ISqlMapper sqlMapper;

			if (isEmbedded)
			{
				XmlDocument sqlMapConfig = Resources.GetEmbeddedResourceAsXmlDocument(fileName);
				sqlMapper = domSqlMapBuilder.Configure(sqlMapConfig);
			}
			else
			{
				sqlMapper = domSqlMapBuilder.Configure(fileName);
			}

			if (connectionString != null && connectionString.Length > 0)
			{
				sqlMapper.DataSource.ConnectionString = connectionString;
			}


			if (sqlMapper != null)
			{
				return sqlMapper;
			}
			else
			{
				throw new FacilityException(string.Format("The IBatisNetIntegration Facility was unable to successfully configure SqlMapper ID [{0}] with File [{1}] that was set to Embedded [{2}].", Model.Name, Model.ExtendedProperties[IBatisNetFacility.MAPPER_CONFIG_FILE].ToString(), Model.ExtendedProperties[IBatisNetFacility.MAPPER_CONFIG_EMBEDDED].ToString()));
			}
		}
        public bool CanResolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model,
                               DependencyModel dependency)
        {

            return Context.CurrentUser != null &&
                   dependency.TargetType == typeof (INotifications);
        }
        /// <summary>
        /// Resolves the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override object Resolve(CreationContext context)
        {
            if (HttpContext.Current == null)
            {
                throw new InvalidOperationException("HttpContext.Current is null. ScopeWebRequestLifestyleManager can only be used in ASP.NET");
            }
            
            string name = (ComponentActivator as AbstractComponentActivator).Model.Name;

            if (_requestScope[name] == null)
            {
                if (!ScopeLifestyleModule.Initialized)
                {
                    string message = "Looks like you forgot to register the http module " +
                        typeof(ScopeLifestyleModule).FullName +
                        "\r\nAdd '<add name=\"ScopeLifestyleModule\" type=\"Castle.Igloo.LifestyleManager.ScopeLifestyleModule, Castle.Igloo\" />' " +
                        "to the <httpModules> section on your web.config";
                    {
					    throw new ConfigurationErrorsException(message);
                    }

                }

                object instance = base.Resolve(context);

                _requestScope.Add(name, instance);
                ScopeLifestyleModule.RegisterForRequestEviction(this, name, instance);
            }

            return _requestScope[name];
        }
			public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model,
			                      DependencyModel dependency)
			{
				return contextHandlerResolver.Resolve(context, contextHandlerResolver, model,
				                                      new DependencyModel(DependencyType.Service, typeof(IBookStore).FullName,
				                                                          typeof(IBookStore), false));
			}
예제 #13
0
		/// <summary>
		/// Creates the <see cref="ISessionFactory"/> from the configuration
		/// </summary>
		/// <param name="context"></param>
		/// <returns></returns>
		public override object Create(CreationContext context)
		{
			RaiseCreatingSessionFactory();
			var configuration = Model.ExtendedProperties[Constants.SessionFactoryConfiguration]
			                    as Configuration;
			return configuration.BuildSessionFactory();
		}
		protected override object Instantiate(CreationContext context)
		{
			object instance = base.Instantiate(context);

			Marshal(instance, Model);

			return instance;
		}
예제 #15
0
 public bool CanResolve(CreationContext context, ISubDependencyResolver parentResolver,
                        ComponentModel model,
                        DependencyModel dependency)
 {
     return dependency.TargetType != null &&
            dependency.TargetType.IsArray &&
            dependency.TargetType.GetElementType().IsInterface;
 }
예제 #16
0
		protected override object Instantiate(CreationContext context)
		{
			String url = (String) Model.ExtendedProperties["remoting.uri"];

			// return Activator.GetObject(Model.Service, url);

			return RemotingServices.Connect( Model.Service, url );
		}
        public override object Create(CreationContext context, Type type)
        {
            var types = new List<Type>(_extraInterfaces.Length + 1);
              types.Add(type);
              types.AddRange(_extraInterfaces);

              return MockFactory.GenerateDynamicMock(types.ToArray());
        }
        protected override object CreateInstance(CreationContext context, object[] arguments, System.Type[] signature)
        {
            // TODO: Support interceptors + copy "use fast create instance" logic from DefaultComponentActivator

            // Support internal and private constructors
            return Activator.CreateInstance(Model.Implementation,
                                            BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public |
                                            BindingFlags.Instance, null, arguments, null, null);
        }
		protected override object Instantiate(CreationContext context)
		{
			object instance = base.Instantiate(context);

			object behavior = ProxyUtil.GetUnproxiedInstance(instance);
			WcfExtensionScope scope = WcfUtils.GetScope(Model);
			WcfUtils.ExtendBehavior(Kernel, scope, behavior);

			return instance;
		}
예제 #20
0
		/// <summary>
		/// Initializes a new instance of the <see cref="CreationContext"/> class.
		/// </summary>
		/// <param name="typeToExtractGenericArguments">The type to extract generic arguments.</param>
		/// <param name="parentContext">The parent context.</param>
		public CreationContext(Type typeToExtractGenericArguments, CreationContext parentContext)
			: this(parentContext.Handler, parentContext.ReleasePolicy, typeToExtractGenericArguments, null, null)
		{
			this.resolutionStack = parentContext.resolutionStack;

			foreach(IHandler handlerItem in parentContext.handlerStack)
			{
				this.handlerStack.Push(handlerItem);
			}
		}
예제 #21
0
		private object InstantiateInMainThread(CreationContext context)
		{
			// The thread associated with the control is the thread in
			// which its windows handle was created, so ensure that the
			// handle is initialized in the context of the main UI thread.

			object component = base.Instantiate(context);
			EnsureHandleCreated(component);
			return component;
		}
        public override object Resolve(CreationContext context)
        {
            // Retrieve from Session, or if not found, resolve via container.
            object result = HttpContext.Current.Session[uniqueKey];

            if (result == null)
                result = HttpContext.Current.Session[uniqueKey] = base.Resolve(context);

            return result;
        }
예제 #23
0
 public bool CanResolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model, DependencyModel dependency)
 {
     try
       {
     return _serviceInterfaceResolver.AttemptResolve(dependency.TargetType, _componentModelSource.Models) != null;
       }
       catch (Exception error)
       {
     throw new ServiceResolutionException(String.Format("Error resolving {0}", model.Name), error);
       }
 }
예제 #24
0
 public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
 {
     // This person is the 'currently logged-in user', i.e. the context needed to resolve which implementation
     // of ISecurityService needs to be returned
     Person person = kernel.Resolve<Person>();
     if (person.UserName == "richard")
     {
         return new InsecureSecurityService();
     }
     return new SecureSecurityService();
 }
		public bool CanResolve(CreationContext context,
			ISubDependencyResolver parentResolver,
			ComponentModel model,
			DependencyModel dependency)
		{
			if (dependency.TargetType.IsArray == false)
				return false;
			Type elementType = dependency.TargetType.GetElementType();

			return kernel.HasComponent(elementType);
		}
예제 #26
0
 public bool CanResolve(CreationContext context, ISubDependencyResolver parentResolver,
     ComponentModel model,
     DependencyModel dependency)
 {
     bool result = dependency.TargetType != null &&
                   dependency.TargetType.GetGenericArguments().Length != 0 &&
                   typeof(IEnumerable<>)
                       .MakeGenericType(dependency.TargetType.GetGenericArguments()[0])
                       .IsAssignableFrom(dependency.TargetType);
     return result;
 }
		protected override object Instantiate(CreationContext context)
		{
			RemotingRegistry registry = (RemotingRegistry) 
				Model.ExtendedProperties["remoting.remoteregistry"];
			
			if (Model.Service.IsGenericType)
			{
				return registry.CreateRemoteInstance(Model.Service);
			}

			return registry.CreateRemoteInstance(Model.Name);
		}
예제 #28
0
 public object Resolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model, DependencyModel dependency)
 {
     try
       {
     ComponentModel resolved = _serviceInterfaceResolver.Resolve(dependency.TargetType, _componentModelSource.Models);
     return _componentModelSource.Kernel[resolved.Service];
       }
       catch (Exception error)
       {
     throw new ServiceResolutionException(String.Format("Error resolving {0}", model.Name), error);
       }
 }
		public DependencyTrackingScope(CreationContext creationContext, ComponentModel model, MemberInfo info,
									   DependencyModel dependencyModel)
		{
			if (dependencyModel.TargetType == typeof (IKernel))
				return;

			this.dependencies = creationContext.Dependencies;

			// We track dependencies in order to detect cycled graphs
			// This prevents a stack overflow
			this.dependencyTrackingKey = TrackDependency(model, info, dependencyModel);
		}
        public override object Resolve(CreationContext context)
        {
            object instance = Local.Data[PerLocalObjectID];

            if (instance == null)
            {
                instance = base.Resolve(context);
                Local.Data[PerLocalObjectID] = instance;
            }

            return instance;
        }
예제 #31
0
        protected override object Instantiate(Castle.MicroKernel.CreationContext context)
        {
            SetupDb4o();

            if (Model.ExtendedProperties[Db4oFacility.HostNameKey] != null)
            {
                return(OpenClient());
            }
            else
            {
                return(OpenLocal());
            }
        }