示例#1
0
        public void Register(Type type, Func <object> createInstanceDelegate, bool singleton = false,
                             bool initialize     = false,
                             string instanceName = null)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (createInstanceDelegate == null)
            {
                throw new ArgumentNullException("createInstanceDelegate");
            }

            var key = new MappingKey(type, singleton, instanceName);

            if (!_mappings.ContainsKey(key))
            {
                if (initialize)
                {
                    if (singleton)
                    {
                        key.Instance = createInstanceDelegate();
                    }
                    else
                    {
                        createInstanceDelegate();
                    }
                }
                _mappings.Add(key, createInstanceDelegate);
            }
        }
示例#2
0
        public void Deregister(Type type, string instanceName = null)
        {
            var           key = new MappingKey(type, default(bool), instanceName);
            Func <object> obj;

            if (_mappings.TryGetValue(key, out obj))
            {
                _mappings.Remove(_mappings.FirstOrDefault(x => x.Value == obj).Key);
            }
        }
示例#3
0
        public object Resolve(Type type, string instanceName = null)
        {
            var           key = new MappingKey(type, default(bool), instanceName);
            Func <object> obj;

            if (_mappings.TryGetValue(key, out obj))
            {
                var mk = _mappings.FirstOrDefault(x => x.Value == obj).Key;

                if (mk.Singleton)
                {
                    return(mk.Instance ?? (mk.Instance = obj()));
                }
                return(obj());
            }
            throw new InvalidOperationException(string.Format("Could not find mapping for type '{0}'", type.FullName));
        }