Beispiel #1
0
    public static void ScanAssemblies <T>(this IRegistrator registrator,
                                          IReuse reuse = null,
                                          Made made    = null,
                                          Setup setup  = null,
                                          IfAlreadyRegistered ifAlreadyRegistered = IfAlreadyRegistered.AppendNotKeyed)
    {
        var serviceTypeOf = typeof(T);
        var scannedTypes  = AssemblyFinder.ScanAssemblies()
                            .Where(assembly =>
        {
            try
            {
                return(assembly.DefinedTypes != null);
            }
            catch
            {
                return(false);
            }
        })
                            .SelectMany(assembly => assembly.DefinedTypes)
                            .Where(type => !type.IsAbstract && serviceTypeOf.GetTypeInfo()
                                   .IsAssignableFrom(type));

        foreach (var eachScannedType in scannedTypes)
        {
            registrator.Register(eachScannedType.AsType(), reuse, made, setup, ifAlreadyRegistered);

            var interfaces = eachScannedType.ImplementedInterfaces;
            foreach (var eachInterface in interfaces)
            {
                registrator.Register(eachInterface, eachScannedType.AsType(), reuse, made, setup, ifAlreadyRegistered);
            }
        }
    }
    public GameObject Spawn()
    {
        GameObject obj = null;

        foreach (GameObject go in m_subPool)
        {
            if (go.activeSelf == false)
            {
                obj = go;
                break;
            }
        }
        if (obj == null)
        {
            obj = GameObject.Instantiate(m_perfab) as GameObject;
            m_subPool.Add(obj);
            //将生成的对象加入到不销毁的父物体中
            obj.transform.SetParent(GameObject.Find("MonsterSceneUse").transform);
        }
        obj.SetActive(true);
        IReuse iResue = obj.GetComponent <IReuse> ();

        if (iResue != null)
        {
            iResue.Spawn();
        }
        return(obj);
    }
Beispiel #3
0
 public static void RegisterDelegate <T>(this IContainerRegistry containerRegistry,
                                         Func <IResolverContext, T> func,
                                         IReuse reuse,
                                         string key = null)
 {
     containerRegistry.GetContainer().RegisterDelegate(func, reuse, serviceKey: key);
 }
 public static void RegisterForAllImplementedInterfaces(this IRegistrator registrator, IEnumerable <Type> types,
                                                        IReuse reuse = null)
 {
     foreach (var type in types)
     {
         registrator.RegisterForAllImplementedInterfaces(type, reuse);
     }
 }
Beispiel #5
0
 public static void Register <TService, TImplementation>(IReuse reuse = null,
                                                         Made made    = null,
                                                         Setup setup  = null,
                                                         IfAlreadyRegistered?ifAlreadyRegistered = null,
                                                         object serviceKey = null) where TImplementation : TService
 {
     _Container.Register <TService, TImplementation>(reuse, made, setup, ifAlreadyRegistered, serviceKey);
 }
 public void RegisterForNavigation <TView, TViewModel>(IReuse reuseItem = null)
     where TView : IPage
     where TViewModel : BaseViewModel
 {
     containerBuilder.Register <TViewModel>(reuse: reuseItem, ifAlreadyRegistered: IfAlreadyRegistered.Keep, setup: DryIoc.Setup.With(trackDisposableTransient: true));
     containerBuilder.Register <TView>(reuse: reuseItem, ifAlreadyRegistered: IfAlreadyRegistered.Keep, setup: DryIoc.Setup.With(trackDisposableTransient: true));
     AddMappings(typeof(TViewModel), typeof(TView));
 }
Beispiel #7
0
 public static void Register(Type serviceAndMayBeImplementationType,
                             IReuse reuse = null,
                             Made made    = null,
                             Setup setup  = null,
                             IfAlreadyRegistered?ifAlreadyRegistered = null,
                             object serviceKey = null)
 {
     _Container.Register(serviceAndMayBeImplementationType, reuse, made, setup, ifAlreadyRegistered, serviceKey);
 }
        public static void RegisterForAllImplementedInterfaces(this IRegistrator registrator, Type type,
                                                               IReuse reuse = null)
        {
            var implementedTypes = type.GetImplementedTypes();

            foreach (var implementedType in implementedTypes)
            {
                registrator.Register(implementedType, type, reuse);
            }
        }
 // Let's define a method to configure our container with auto-mocking of interfaces or abstract classes.
 // Optional `reuse` parameter will allow to specify a mock reuse.
 private IContainer WithAutoMocking(IContainer container, IReuse reuse = null) =>
     container.With(rules => rules.WithUnknownServiceResolvers(request =>
     {
         var serviceType = request.ServiceType;
         if (!serviceType.IsAbstract) // Mock interface or abstract class only.
             return null;
         return _mockFactories.GetOrAdd(serviceType,
             type => new ReflectionFactory(reuse: reuse,
                 made: Made.Of(() => Substitute.For(new[] { type }, null))));
     }));
Beispiel #10
0
 public static IContainer WithRegistration <TService, TImpl>(
     this IContainer container,
     IReuse reuse
     ) where TImpl : TService
 {
     return(container.WithRegistration(
                typeof(TService),
                typeof(TImpl),
                reuse
                ));
 }
 private void RegisterInternal <TService>(
     Func <IContainer, TService> func,
     IReuse reuse,
     IfRegistered ifRegistered = IfRegistered.AppendNew)
 {
     _dryContainer.RegisterDelegate(
         c => func.Invoke(c.Resolve <IContainer>()),
         reuse,
         null,
         MapIfAlreadyRegistered(ifRegistered));
 }
 public void UnSpawn(GameObject obj)
 {
     if (m_subPool.Contains(obj))
     {
         IReuse iResue = obj.GetComponent <IReuse> ();
         if (iResue != null)
         {
             iResue.UnSpawn();
         }
         obj.SetActive(false);
     }
 }
    // Let's define a method to configure our container with auto-mocking of interfaces or abstract classes.
    // Optional `reuse` parameter will allow to specify a mock reuse.
    private IContainer WithAutoMocking(IContainer container, IReuse reuse = null) =>
    container.With(rules => rules.WithUnknownServiceResolvers(request =>
    {
        var serviceType = request.ServiceType;
        if (!serviceType.IsAbstract)     // Mock interface or abstract class only.
        {
            return(null);
        }

        return(_mockFactories.GetOrAdd(serviceType,
                                       _ => new ReflectionFactory(reuse: reuse,
                                                                  made: Made.Of(typeof(Mock).Method(nameof(Mock.Of))))));
    }));
Beispiel #14
0
 private static IContainer WithRegistration(
     this IContainer container,
     Type serviceType,
     Type implementationType,
     IReuse reuse
     )
 {
     return(container.With(
                o => o.Register(
                    serviceType,
                    implementationType,
                    reuse)
                ));
 }
    // Let's define a method to configure our container with auto-mocking of interfaces or abstract classes.
    // Optional `reuse` parameter will allow to specify a mock reuse.
    private IContainer WithAutoMocking(IContainer container, IReuse reuse = null) =>
    container.With(rules => rules.WithDynamicRegistration((serviceType, serviceKey) =>
    {
        if (!serviceType.IsAbstract)     // Mock interface or abstract class only.
        {
            return(null);
        }

        var d = _mockRegistrations.GetOrAdd(serviceType,
                                            type => new DynamicRegistration(
                                                DelegateFactory.Of(r => Substitute.For(new[] { serviceType }, Empty <object>()), reuse)));

        return(new[] { d });
    },
                                                          DynamicRegistrationFlags.Service | DynamicRegistrationFlags.AsFallback));
Beispiel #16
0
 private static IContainer WithRegistration <T>(
     this IContainer container,
     Type serviceType,
     Func <IResolverContext, T> factory,
     string serviceKey,
     IReuse reuse
     )
 {
     return(container.With(
                o => o.RegisterDelegate(
                    serviceType,
                    c => factory(c),
                    reuse,
                    serviceKey: serviceKey
                    )
                ));
 }
Beispiel #17
0
        private static IReuse ConvertLifetimeToReuse(ServiceLifetime lifetime, IReuse singletonReuse = null)
        {
            switch (lifetime)
            {
            case ServiceLifetime.Singleton:
                return(singletonReuse ?? Reuse.Singleton);

            case ServiceLifetime.Scoped:
                return(Reuse.ScopedOrSingleton);    // note: because the infrastructure services may be resolved w/out scope

            case ServiceLifetime.Transient:
                return(Reuse.Transient);

            default:
                throw new ArgumentOutOfRangeException(nameof(lifetime), lifetime, "Not supported lifetime");
            }
        }
Beispiel #18
0
        /// <summary>
        /// Регистрация сборок в DryIoc-контейнере
        /// </summary>
        /// <param name="services">Коллекция сервисов</param>
        /// <param name="assemblies">Список сборок</param>
        /// <returns>IContainer</returns>
        protected IContainer ConfigureDependencies(IServiceCollection services, params string[] assemblies)
        {
            // Register assemblies
            IEnumerable <AssemblyName> assemblyNames = Assembly.GetEntryAssembly()
                                                       .GetReferencedAssemblies()
                                                       .Where(a => assemblies.Length == 0 || assemblies.Contains(a.Name))
                                                       .ToList();

            IList <Assembly> implTypeAssemblies = new List <Assembly>(assemblyNames.Count());

            foreach (AssemblyName an in assemblyNames)
            {
                implTypeAssemblies.Add(Assembly.Load(an));
            }

            IContainer container = new Container().WithDependencyInjectionAdapter(services);

            container.RegisterMany(implTypeAssemblies, (registrator, types, type) =>
            {
                IgnoreRegistrationAttribute ignoreAttr = (IgnoreRegistrationAttribute)type.GetCustomAttribute(typeof(IgnoreRegistrationAttribute));
                if (ignoreAttr == null)
                {
                    // all dispatchers --> Reuse.InCurrentScope
                    IReuse reuse = type.IsAssignableTo(typeof(ICommandDispatcher)) ||
                                   type.IsAssignableTo(typeof(IJobDispatcher)) ||
                                   type.IsAssignableTo(typeof(IQueryDispatcher))
                        ? Reuse.InCurrentScope
                        : Reuse.Transient;

                    registrator.RegisterMany(types, type, reuse);

                    // interceptors
                    if (type.IsClass)
                    {
                        InterceptedObjectAttribute attr = (InterceptedObjectAttribute)type.GetCustomAttribute(typeof(InterceptedObjectAttribute));
                        if (attr != null)
                        {
                            Type serviceType = attr.ServiceInterfaceType ?? type.GetImplementedInterfaces().FirstOrDefault();
                            registrator.RegisterInterfaceInterceptor(serviceType, attr.InterceptorType);
                        }
                    }
                }
            });

            return(container);
        }
Beispiel #19
0
        private IReadOnlyCollection <Type> RegisterTypes(IDiscoveryService discovery)
        {
            ITypeFactory[] factories = discovery.GetCustomFactories().ToArray();
            var            normal    = new List <Type>();
            var            custom    = new List <Type>(); // We need to store these to return them at the end

            foreach (Type type in discovery.GetDiscoveredTypes())
            {
                Func <IResolver, object> factory = this.GetFactory(factories, type);
                if (factory == null)
                {
                    normal.Add(type);
                }
                else
                {
                    this.adapter.Container.RegisterDelegate(
                        type,
                        factory,
                        ifAlreadyRegistered: IfAlreadyRegistered.Replace);

                    custom.Add(type);
                }
            }

            this.adapter.Container.RegisterMany(
                normal.Where(IsImplementationType),
                (IRegistrator registrator, Type[] serviceTypes, Type implementingType) =>
            {
                IReuse reuse =
                    serviceTypes.Any(discovery.IsSingleInstance) ?
                    Reuse.Singleton : Reuse.Transient;

                registrator.RegisterMany(
                    serviceTypes,
                    implementingType,
                    reuse,
                    ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            },
                nonPublicServiceTypes: true);

            // Normal probably has the most types in it, so fold the others into it
            normal.AddRange(custom);
            return(normal);
        }
        public void RegisterFactory <T1, T2, T3, TResult>(Func <T1, T2, T3, TResult> factory, RegistrationMode mode, RegistrationLifestyle lifestyle) where TResult : class
        {
            IReuse reuse = null;

            switch (lifestyle)
            {
            case RegistrationLifestyle.Singleton:
                reuse = new SingletonReuse();
                break;

            case RegistrationLifestyle.SingletonPerScope:
                reuse = new CurrentScopeReuse();
                break;

            case RegistrationLifestyle.SingletonPerObjectGraph:
                throw new NotSupportedException("");
            }

            _container.RegisterDelegate(r => factory(r.Resolve <T1>(), r.Resolve <T2>(), r.Resolve <T3>()), reuse);
        }
Beispiel #21
0
        private void Setup(IReuse reuse)
        {
            _container = new Container();
            _container.Register <IRepository, Repository>(reuse);
            _container.Register <IAuthenticationService, AuthenticationService>(reuse);
            _container.Register <UserController, UserController>(reuse);

            _container.Register <IWebService, WebService>(reuse);
            _container.Register <IAuthenticator, Authenticator>(reuse);
            _container.Register <IStockQuote, StockQuote>(reuse);
            _container.Register <IDatabase, Database>(reuse);
            _container.Register <IErrorHandler, ErrorHandler>(reuse);

            _container.Register <IService1, Service1>(reuse);
            _container.Register <IService2, Service2>(reuse);
            _container.Register <IService3, Service3>(reuse);
            _container.Register <IService4, Service4>(reuse);

            _container.Register <ILogger, Logger>(reuse);
        }
        public void Registration(IEnumerable <RegistrationDefinition> definitions)
        {
            foreach (var definition in definitions)
            {
                IReuse reuse = null;

                switch (definition.RegistrationLifestyle)
                {
                case RegistrationLifestyle.Singleton:
                    reuse = new SingletonReuse();
                    break;

                case RegistrationLifestyle.SingletonPerScope:
                    reuse = new CurrentScopeReuse();
                    break;
                }

                PropertiesAndFieldsSelector madeOf = null;

                if (definition.MemberInjectionList != null)
                {
                    madeOf = PropertiesAndFields.Of;

                    foreach (var injectionInfo in definition.MemberInjectionList)
                    {
                        switch (injectionInfo.InjectionType)
                        {
                        case MemberInjectionType.Field:
                        case MemberInjectionType.Property:
                            madeOf = madeOf.Name(injectionInfo.MemberName);
                            break;

                        case MemberInjectionType.Method:
                            throw new NotSupportedException();
                        }
                    }
                }

                _container.Register(definition.ExportType, definition.ActivationType, reuse, madeOf);
            }
        }
Beispiel #23
0
        /// <summary>Creates new container from original one with <see cref="HttpContextScopeContext"/>.
        /// Then registers MVC controllers in container,
        /// sets <see cref="DryIocFilterAttributeFilterProvider"/> as filter provider,
        /// and at last sets container as <see cref="DependencyResolver"/>.</summary>
        /// <param name="container">Original container.</param>
        /// <param name="controllerAssemblies">(optional) By default uses <see cref="BuildManager.GetReferencedAssemblies"/>.</param>
        /// <param name="scopeContext">(optional) Specific scope context to use, by default MVC uses <see cref="HttpContextScopeContext"/>
        /// (if container does not have its own context specified).</param>
        /// <param name="throwIfUnresolved">(optional) Instructs DryIoc to throw exception
        /// for unresolved type instead of fallback to default Resolver.</param>
        /// <param name="controllerReuse">(optional) Defaults to <see cref="Reuse.InWebRequest"/></param>
        /// <returns>New container with applied Web context.</returns>
        public static IContainer WithMvc(this IContainer container,
                                         IEnumerable <Assembly> controllerAssemblies = null,
                                         IScopeContext scopeContext          = null,
                                         Func <Type, bool> throwIfUnresolved = null,
                                         IReuse controllerReuse = null)
        {
            container.ThrowIfNull();

            if (container.ScopeContext == null)
            {
                container = container.With(scopeContext: scopeContext ?? new HttpContextScopeContext());
            }

            container.RegisterMvcControllers(controllerAssemblies, controllerReuse);

            container.SetFilterAttributeFilterProvider(FilterProviders.Providers);

            DependencyResolver.SetResolver(new DryIocDependencyResolver(container, throwIfUnresolved));

            return(container);
        }
 public static void RegisterForAllImplementedInterfaces <T>(this IRegistrator registrator, IReuse reuse = null)
 => registrator.RegisterForAllImplementedInterfaces(typeof(T));
Beispiel #25
0
        public static void RegisterViewsForViewModels(this IContainer container, IReuse reuse)
        {
            var types = Assembly.GetCallingAssembly().GetTypes().Where(x => x.Name.EndsWith("View"));

            container.RegisterMany(types, reuse, serviceTypeCondition: type => type.Name.StartsWith(nameof(IViewFor)) && type.IsGenericType);
        }
 public CustomDelegateWrapper(IReuse reuse = null, Setup setup = null)
     : base(reuse, setup)
 {
 }
Beispiel #27
0
 public static void Register <IService, Service>(this ZyanServer self, IReuse reuse)
     where Service : IService
 {
     self.Container.Register <IService, Service>(reuse);
 }
Beispiel #28
0
        public static void RegisterAll <T>([NotNull] this IContainer container, [NotNull] Assembly assembly, [CanBeNull] IReuse reuse = null)
        {
            if (container is null)
            {
                throw new ArgumentNullException(nameof(container));
            }

            if (assembly is null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }

            foreach (Type type in assembly.GetTypes())
            {
                if (!typeof(T).IsAssignableFrom(type))
                {
                    continue;
                }

                if (type.IsAbstract)
                {
                    continue;
                }

                container.Register(typeof(T), type, reuse);
            }
        }
 public static void RegisterDelegate <TDep1, TDep2, TDep3, TService>(
     this IRegistrator r, Func <TDep1, TDep2, TDep3, TService> f,
     IReuse reuse = null, Setup setup = null, IfAlreadyRegistered?ifAlreadyRegistered = null, object serviceKey = null) =>
 r.Register <TService>(made: Made.Of(FactoryMethod.Of(f.GetType().GetMethod("Invoke"), f)),
                       reuse: reuse, setup: setup, ifAlreadyRegistered: ifAlreadyRegistered, serviceKey: serviceKey);
Beispiel #30
0
        /// <summary>Registers controllers types in container with InWebRequest reuse.</summary>
        /// <param name="container">Container to register controllers to.</param>
        /// <param name="controllerAssemblies">(optional) Uses <see cref="BuildManager.GetReferencedAssemblies"/> by default.</param>
        /// <param name="controllerReuse">(optional) Defaults to <see cref="Reuse.InWebRequest"/></param>
        public static void RegisterMvcControllers(this IContainer container,
                                                  IEnumerable <Assembly> controllerAssemblies = null, IReuse controllerReuse = null)
        {
            controllerAssemblies = controllerAssemblies ?? GetReferencedAssemblies();
            controllerReuse      = controllerReuse ?? Reuse.InWebRequest;

            container.RegisterMany(controllerAssemblies, IsController, controllerReuse,
                                   FactoryMethod.ConstructorWithResolvableArguments);
        }