Пример #1
0
            public ScopedFactory(IResolverContext context)
            {
                _scope = context.OpenScope();

                //use this factory within it`s scope
                _scope.UseInstance <IScopedFactory>(this);
            }
Пример #2
0
        public void Register(ServiceRegistration registration)
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }

            if (!IsScoped && container == null)
            {
                throw new InvalidOperationException("The container was not initialized.");
            }

            if (IsScoped && registration.Instance == null)
            {
                throw new ArgumentException("Cannot register a service in a scope");
            }

            try {
                lock (this) {
                    var serviceType        = registration.ServiceType;
                    var service            = registration.Instance;
                    var serviceName        = registration.ServiceKey;
                    var implementationType = registration.ImplementationType;

                    var reuse = Reuse.Transient;

                    if (!String.IsNullOrEmpty(registration.Scope))
                    {
                        reuse = Reuse.InCurrentNamedScope(registration.Scope);
                    }
                    else if (!String.IsNullOrEmpty(scopeName))
                    {
                        reuse = Reuse.InCurrentNamedScope(scopeName);
                    }

                    if (service == null)
                    {
                        container.Register(serviceType, implementationType, serviceKey: serviceName, reuse: reuse);
                    }
                    else if (!String.IsNullOrEmpty(scopeName))
                    {
                        resolver.UseInstance(serviceType, service, serviceKey: serviceName);
                    }
                    else
                    {
                        container.UseInstance(serviceType, service, serviceKey: serviceName);
                    }
                }
            } catch (ServiceException) {
                throw;
            } catch (Exception ex) {
                throw new ServiceException("Error when registering service.", ex);
            }
        }