Beispiel #1
0
        public static void RegisterDependencies()
        {
            var builder = new ContainerBuilder();
            var typeFinder = new AppDomainTypeFinder();

            var dependencyRegistrars = typeFinder.FindClassesOfType<IDependencyRegistrar>();
            foreach (var r in dependencyRegistrars)
            {
                try
                {
                    var instance = (IDependencyRegistrar)Activator.CreateInstance(r);
                    instance.RegisterDependencies(builder,typeFinder);

                }
                catch (Exception ex)
                {
                    LogHelper.Error(r, "Could No Register Dependencies in " + r.Name, ex);
                }
            }

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
        /// <summary>
        /// Add and configure services
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        /// <returns>Service provider</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            //find startup configurations provided by other assemblies
            var typeFinder            = new AppDomainTypeFinder();
            var startupConfigurations = typeFinder.FindClassesOfType <INopStartup>();

            //create and sort instances of startup configurations
            var instances = startupConfigurations
                            //.Where(startup => PluginManager.FindPlugin(startup)?.Installed ?? true) //ignore not installed plugins
                            .Select(startup => (INopStartup)Activator.CreateInstance(startup))
                            .OrderBy(startup => startup.Order);

            //configure services
            foreach (var instance in instances)
            {
                instance.ConfigureServices(services, configuration);
            }

            //register mapper configurations
            AddAutoMapper(services, typeFinder);

            //register dependencies
            var nopConfig = services.BuildServiceProvider().GetService <NopConfig>();

            RegisterDependencies(nopConfig, services, typeFinder);

            //run startup tasks
            //if (!nopConfig.IgnoreStartupTasks)
            //RunStartupTasks(typeFinder);

            //resolve assemblies here. otherwise, plugins can throw an exception when rendering views
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            return(_serviceProvider);
        }
 //private static bool _isAutoSubscribe = false;
 public static void init()
 {
     if (!inited)
     {
         lock (lockObj)
         {
             if (!inited)
             {
                 bool?isAutoSubscribe = ConfigManager.Instance.Get <bool?>("event_IsAutoSubscribe");
                 if (isAutoSubscribe.HasValue && !isAutoSubscribe.Value)
                 {
                     inited = true;
                     return;
                 }
                 var typeFinder = new AppDomainTypeFinder();
                 var consumers  = typeFinder.FindClassesOfType(typeof(IConsumer <>)).ToList();
                 foreach (var consumer in consumers)
                 {
                     EventAutoSubscribeAttribute autoEvent = consumer.GetCustomAttribute <EventAutoSubscribeAttribute>();
                     if (autoEvent != null && !autoEvent.IsAutoSubscribe)
                     {
                         continue;
                     }
                     InternalRegisterConsumerType(consumer);
                 }
                 inited = true;
             }
         }
     }
 }
Beispiel #4
0
        public static void SetUpDictinoaryResources()
        {
            var typeFinder = new AppDomainTypeFinder();
            var allBaseContent = typeFinder.FindClassesOfType<PublishedContentExtended>(true);
            var dicService = new DictionaryService(ApplicationContext.Current.Services.LocalizationService);

            var dictionaryResourceAttr =
                allBaseContent.SelectMany(t => t.GetProperties())
                    .Where(p => p.GetCustomAttributes(typeof(DictionaryResourceAttribute), false).Any())
                    .Select(
                        p =>
                            new Tuple<DictionaryResourceAttribute, string>((DictionaryResourceAttribute)
                                p.GetCustomAttributes(typeof(DictionaryResourceAttribute), false).First(), p.DeclaringType.Name)
                           )
                    .ToList();

            var language = dicService.GetLanguageByCultureCode("he-IL");
            if (language == null)
                return;
            dictionaryResourceAttr.ForEach(x =>
            {
                var resourceName = string.Format("{0}.{1}", x.Item2, x.Item1.ResourceName);
                dicService.AddOrSet(resourceName, x.Item1.DefaultValue, language);

            });
        }
        /// <summary>
        /// Executes an Down migration
        /// </summary>
        /// <param name="assembly">Assembly to find the migration;
        /// leave null to search migration on the whole application pull</param>
        public virtual void ApplyDownMigrations(Assembly assembly = null)
        {
            //do not inject services via constructor because it'll cause installation fails
            var migrationRunner = EngineContext.Current.Resolve <IMigrationRunner>();
            var migrationVersionInfoRepository = EngineContext.Current.Resolve <IRepository <MigrationVersionInfo> >();
            var typeFinder = new AppDomainTypeFinder();

            //executes a Down migrations
            foreach (var migration in assembly == null ? typeFinder.FindClassesOfType <Migration>() : typeFinder.FindClassesOfType <Migration>(new[] { assembly }))
            {
                try
                {
                    var migrationAttribute = migration
                                             .GetCustomAttributes(typeof(MigrationAttribute), false)
                                             .OfType <MigrationAttribute>()
                                             .FirstOrDefault();

                    foreach (var migrationVersionInfo in migrationVersionInfoRepository.Table.Where(p => p.Version == migrationAttribute.Version).ToList())
                    {
                        migrationVersionInfoRepository.Delete(migrationVersionInfo);
                    }

                    var downMigration = EngineContext.Current.ResolveUnregistered(migration) as IMigration;
                    migrationRunner.Down(downMigration);
                }
                catch
                {
                    // ignored
                }
            }
        }
        /// <summary>
        /// Executes all found (and unapplied) migrations
        /// </summary>
        /// <param name="assembly">Assembly to find the migration;
        /// leave null to search migration on the whole application pull</param>
        public virtual void ApplyUpMigrations(Assembly assembly = null)
        {
            var runner = EngineContext.Current.Resolve <IMigrationRunner>();

            //find database mapping configuration by other assemblies
            var typeFinder = new AppDomainTypeFinder();
            var migrations = (assembly == null ? typeFinder.FindClassesOfType <AutoReversingMigration>() : typeFinder.FindClassesOfType <AutoReversingMigration>(new List <Assembly> {
                assembly
            }))
                             .Select(migration => migration
                                     .GetCustomAttributes(typeof(MigrationAttribute), false)
                                     .OfType <MigrationAttribute>()
                                     .FirstOrDefault()).Where(migration => migration != null && runner.HasMigrationsToApplyUp(migration.Version)).OrderBy(migration => migration.Version)
                             .ToList();

            foreach (var migration in migrations)
            {
                try
                {
                    runner.MigrateUp(migration.Version);
                }
                catch (MissingMigrationsException)
                {
                    // ignore
                }
                catch (Exception ex)
                {
                    if (!(ex.InnerException is SqlException))
                    {
                        throw;
                    }
                }
            }
        }
        public static IServiceProvider ConfigureServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.ConfigureInfrastructureServices(configuration);

            var mvcBuilder = services.AddMvcService();

            mvcBuilder.AddMvcOptions(options =>
            {
                options.ModelMetadataDetailsProviders.Add(new EntityDataAnnotationsMetadataProvider());
            });

            var typeFinder = new AppDomainTypeFinder();

            var configureServiceTypes     = typeFinder.FindTypes <IConfigureServices>();
            var configureServiceInstances =
                configureServiceTypes.Select(x => (IConfigureServices)Activator.CreateInstance(x))
                .OrderBy(x => x.Order);

            foreach (var configureService in configureServiceInstances)
            {
                configureService.ConfigureServices(services, configuration);
            }


            var serviceProvider = services.BuildServiceProvider();

            DependencyResolver.Current.SetServiceProvider(serviceProvider);

            return(serviceProvider);
        }
        private static void AutoRegisterService()
        {
            var _typeFinder = new AppDomainTypeFinder();
            var bsTypes     = _typeFinder.FindClassesOfType <IBufferServiceRegistrar>();
            var bsInstances = new List <IBufferServiceRegistrar>();

            foreach (var bsType in bsTypes)
            {
                bsInstances.Add((IBufferServiceRegistrar)Activator.CreateInstance(bsType));
            }
            bsInstances = bsInstances.AsQueryable().OrderBy(t => t.Order).ToList();
            foreach (var bsRegistrar in bsInstances)
            {
                if (_processors == null)
                {
                    _processors = new List <BufferProcessorService>();
                    bsRegistrar.Register(_processors);
                }
                else
                {
                    bsRegistrar.Register(_processors);
                }
                logger.Info(string.Format("数据缓存服务,数据处理器注册完成,类型:{0}", bsRegistrar.GetType().FullName));
            }
            logger.Info(string.Format("数据缓存服务,已完成{0}个数据处理器注册", bsInstances.Count));
        }
Beispiel #9
0
        /// <summary>
        /// 配置映射直接采用异步启动
        /// </summary>
        /// <returns></returns>
        public static Task InitializeAsync()
        {
            return(Task.Factory.StartNew(() =>
            {
                //类型寻找
                var typeFinder = new AppDomainTypeFinder()
                {
                    //从指定的程序集加载Types
                    AssemblyNames = new List <string>
                    {
                        "FlyBirdYoYo.DomainEntity",
                    }
                };

                var entityTypes = typeFinder.FindClassesOfType(typeof(BaseEntity));

                ////////////var types = from type in Assembly.Load(@namespace).GetTypes()
                ////////////            where type.IsClass && type.Namespace == @namespace
                ////////////            select type;

                if (entityTypes.IsNotEmpty())
                {
                    //创建指定的对象实例的Mapper
                    entityTypes.AsParallel().ForAll(type =>
                    {
                        //////////////////var mapper = (SqlMapper.ITypeMap)Activator.CreateInstance(typeof(ColumnAttributeTypeMapper<>)
                        //////////////////     .MakeGenericType(type));
                        ///上面是基于反射的方式创建的Mapper实例--尽量少些反射 能不用反射就不用反射  嘿嘿----by wali-2018-10-31
                        var mapper = new ColumnAttributeTypeMapper(type);
                        SqlMapper.SetTypeMap(type, mapper);
                    });
                }
            }));
        }
Beispiel #10
0
        /// <summary>
        /// 配置映射直接采用异步启动
        /// </summary>
        /// <returns></returns>
        public static Task InitializeAsync()
        {
            return(Task.Factory.StartNew(() =>
            {
                //类型寻找
                var typeFinder = new AppDomainTypeFinder()
                {
                    //从指定的程序集加载Types
                    AssemblyNames = new List <string>
                    {
                        "FlyBirdYoYo.DomainEntity",
                    }
                };

                var entityTypes = typeFinder.FindClassesOfType(typeof(BaseEntity));


                if (entityTypes.IsNotEmpty())
                {
                    //创建指定的对象实例的Mapper
                    entityTypes.AsParallel().ForAll(type =>
                    {
                        var mapper = new ColumnAttributeTypeMapper(type);
                        SqlMapper.SetTypeMap(type, mapper);
                    });
                }
            }));
        }
Beispiel #11
0
        public static void RegisterAutofacEvents(this ContainerBuilder builder)
        {
            var typeFinder     = new AppDomainTypeFinder();
            var consumers      = typeFinder.FindClassesOfType(typeof(IConsumer <>)).ToList();
            var asyncconsumers = typeFinder.FindClassesOfType(typeof(IAsyncConsumer <>)).ToList();

            foreach (var consumer in consumers)
            {
                builder.RegisterType(consumer)
                .As(consumer.FindInterfaces((type, criteria) =>
                {
                    var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                    return(isMatch);
                }, typeof(IConsumer <>)))
                .InstancePerLifetimeScope();
            }
            foreach (var consumer in asyncconsumers)
            {
                builder.RegisterType(consumer)
                .As(consumer.FindInterfaces((type, criteria) =>
                {
                    var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                    return(isMatch);
                }, typeof(IAsyncConsumer <>)))
                .InstancePerLifetimeScope();
            }
            builder.RegisterType <EventPublisher>().As <IEventPublisher>().InstancePerLifetimeScope();
            builder.RegisterType <EventsSubscriptionService>().As <ISubscriptionService>().InstancePerLifetimeScope();
        }
Beispiel #12
0
        public static InitializerContext IocInitialize(this InitializerContext context, Action <IocInitializer> configure = null, ITypeFinder typeFinder = null)
        {
            var initializer = new IocInitializer();

            initializer.Builder = new ContainerBuilder();
            initializer.Builder.RegisterType <Configs>().As <ISettings>().SingleInstance();
            initializer.Builder.RegisterType <Configs>().SingleInstance();
            initializer.Builder.RegisterType <MemoryCacheManager>().As <ICacheProvider>().SingleInstance();
            if (typeFinder == null)
            {
                typeFinder = new AppDomainTypeFinder();
            }
            initializer.Builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();
            initializer.Builder.RegisterType <EventPublisher>().As <IEventPublisher>().SingleInstance();
            var drInstancees = typeFinder.CreateInstanceOnFoundType <IDependencyRegistrar>();

            drInstancees = drInstancees.AsQueryable().OrderBy(t => t.Order).ToList();
            foreach (var dependencyRegistrar in drInstancees)
            {
                dependencyRegistrar.Register(initializer.Builder, typeFinder);
            }
            if (configure != null)
            {
                configure.Invoke(initializer);
            }
            context.Initialzer.Add(initializer);
            return(context);
        }
Beispiel #13
0
        private void PrePeocess(IList <ScheduledTask> list)
        {
            if (list.Count > 0)
            {
                return;
            }

            var taskTypes = new AppDomainTypeFinder().FindClassesOfType <IRunnableTask>();

            if (taskTypes != null)
            {
                bool isCentralInst = string.IsNullOrWhiteSpace(InstitutionCode) || InstitutionCode.Equals(Utilities.INST_DEFAULT_CODE, StringComparison.InvariantCultureIgnoreCase);
                foreach (var type in taskTypes)
                {
                    var instance = Activator.CreateInstance(type) as IRunnableTask;
                    if (instance != null)
                    {
                        if (!isCentralInst && instance.OwnershipType == OwnershipType.CentralOnly)
                        {
                            continue;
                        }

                        list.Add(instance.DefaultTaskPlan);
                    }
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// Add and configure any of the middleware
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            var mappingBuilder = new FluentMappingBuilder(NopDataConnection.AdditionalSchema);

            //find database mapping configuration by other assemblies
            var typeFinder         = new AppDomainTypeFinder();
            var typeConfigurations = typeFinder.FindClassesOfType <IMappingConfiguration>().ToList();

            foreach (var typeConfiguration in typeConfigurations)
            {
                var mappingConfiguration = (IMappingConfiguration)Activator.CreateInstance(typeConfiguration);
                mappingConfiguration.ApplyConfiguration(mappingBuilder);
            }

            //further actions are performed only when the database is installed
            if (!DataSettingsManager.DatabaseIsInstalled)
            {
                return;
            }

            DataConnection.DefaultSettings = Singleton <DataSettings> .Instance;

            MappingSchema.Default.SetConvertExpression <string, Guid>(strGuid => new Guid(strGuid));

            services
            // add common FluentMigrator services
            .AddFluentMigratorCore()
            .ConfigureRunner(rb => rb.SetServer()
                             .WithVersionTable(new MigrationVersionInfo())
                             // define the assembly containing the migrations
                             .ScanIn(typeConfigurations.Select(p => p.Assembly).Distinct().ToArray()).For.Migrations());
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(x =>
            {
                x.ReturnHttpNotAcceptable = true;
            }).AddXmlDataContractSerializerFormatters();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString(@"/api/login/reLogin");
            });

            services.AddAutoMapper(typeof(CompanyProfile));

            Configuration.GetSection("ConfigEntity").Bind(ConfigEntity.Instance);


            var diTypes = AppDomainTypeFinder.GetSubClassType(typeof(IDIBuilder));

            diTypes.Foreach(x =>
            {
                var instance = (IDIBuilder)Activator.CreateInstance(x);
                instance.DIBuilder(services);
            });
        }
Beispiel #16
0
        public static void Init()
        {
            var finder      = new AppDomainTypeFinder();
            var mcTypes     = finder.FindClassesOfType(typeof(IMapperConfiguration));
            var mcInstances = new List <IMapperConfiguration>();

            foreach (var mcType in mcTypes)
            {
                mcInstances.Add((IMapperConfiguration)Activator.CreateInstance(mcType));
            }

            //sort
            mcInstances = mcInstances.AsQueryable().OrderBy(t => t.Order).ToList();

            //get configurations
            var configurationActions = new List <Action <IMapperConfigurationExpression> >();

            foreach (var mc in mcInstances)
            {
                configurationActions.Add(mc.GetConfiguration());
            }

            //register
            AutoMapperConfiguration.Init(configurationActions);
        }
        public void TypeFinder_Benchmark_Findings()
        {
            var finder = new AppDomainTypeFinder();

            var type = finder.FindClassesOfType<ISomeInterface>();
            type.Count().ShouldEqual(1);
            typeof (ISomeInterface).IsAssignableFrom(type.FirstOrDefault()).ShouldBeTrue();
        }
        public void ConfigureContainer(ContainerBuilder containerBuilder, IConfiguration configuration)
        {
            var typeFinder = new AppDomainTypeFinder();

            containerBuilder.RegisterType <HarFluentValidationValidatorFactory>().As <IValidatorFactory>().InstancePerLifetimeScope();

            containerBuilder.RegisterAssemblyTypes(typeFinder.GetAssemblies().ToArray()).AsClosedTypesOf(typeof(IValidator <>)).InstancePerLifetimeScope();
        }
Beispiel #19
0
        public void FindType()
        {
            var typeFinder = new AppDomainTypeFinder();

            var cacheType = typeFinder.FindTypes <ICache>();

            Assert.AreEqual(cacheType.ToList().Count, 2); // memoryCache and RedisCache. 抽象的 EmptyCache 不会被查找。
        }
            public void TypeFinder_Benchmark_Findings()
            {
                var finder = new AppDomainTypeFinder();

                var type = finder.FindClassesOfType<ISomeInterface>();
                Assert.AreEqual(type.Count(),1);
                Assert.AreEqual(typeof(ISomeInterface).IsAssignableFrom(type.FirstOrDefault()), true);
            }
Beispiel #21
0
        public void TypeFinder_Benchmark_Findings()
        {
            var finder = new AppDomainTypeFinder();

            var type = finder.FindClassesOfType <ISomeInterface>();

            type.Count().ShouldEqual(1);
            typeof(ISomeInterface).IsAssignableFrom(type.FirstOrDefault()).ShouldBeTrue();
        }
        private static void RegisterExamineEventConsumers(ContainerBuilder builder)
        {
            var typeFinder = new AppDomainTypeFinder();
            var consumers  = typeFinder.FindClassesOfType <IExamineEventsConsumer>(true);

            foreach (var consumer in consumers)
            {
                builder.RegisterType(consumer).As <IExamineEventsConsumer>().SingleInstance();
            }
        }
        public void Check_how_many_classes_inherit_from_this_IInterface()
        {
            AppDomainTypeFinder appDomainTypeFinder = new AppDomainTypeFinder();
            IEnumerable <Type>  result = appDomainTypeFinder.FindClassesOfType <IInterface>();

            int sevenInheritingClasses = 7;

            Assert.AreEqual(sevenInheritingClasses, result.Count());
            Assert.IsTrue(result.Contains(typeof(First06)));
            Assert.IsFalse(result.Contains(typeof(First08)));
        }
Beispiel #24
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var typeFinder         = new AppDomainTypeFinder();
            var typeConfigurations = typeFinder.FindClassesOfType <IMappingConfiguration>().ToList();

            foreach (var typeConfiguration in typeConfigurations)
            {
                var mappingConfiguration = (IMappingConfiguration)Activator.CreateInstance(typeConfiguration);
                mappingConfiguration.ApplyConfiguration(modelBuilder);
            }
        }
Beispiel #25
0
        public static void Initialize()
        {
            if (_container != null)
            {
                throw new InvalidOperationException("Dependency Container already initialized.");
            }
            var builder = new ContainerBuilder();

            _typeFinder = new AppDomainTypeFinder();
            // Register Logger
            _logger = LogManager.GetLogger("Demo");
            XmlConfigurator.Configure();
            builder.RegisterInstance(_logger).As <ILog>().SingleInstance();
            builder.RegisterInstance(_typeFinder).As <ITypeFinder>().SingleInstance();

            // Register Web Types
            builder.RegisterModule(new AutofacWebTypesModule());

            //// Closed for Layout View Issue: https://github.com/autofac/Autofac/issues/349#issuecomment-33025529
            // Register ViewPages
            //builder.RegisterSource(new ViewRegistrationSource());

            // Register Controllers
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // Register Action Filters
            builder.RegisterFilterProvider();

            //FluentValidation
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
            ModelValidatorProviders.Providers.Clear();
            FluentValidationModelValidatorProvider.Configure(provider =>
            {
                provider.ValidatorFactory             = new AutofacValidatorFactory();
                provider.AddImplicitRequiredValidator = false;
            });
            //var fluentValidation = new FluentValidationModelValidatorProvider(new AutofacValidatorFactory())
            //{
            //    AddImplicitRequiredValidator = false
            //};
            //// builder.RegisterType<FluentValidationModelValidatorProvider>().As<ModelValidatorProvider>();
            //builder.RegisterInstance(fluentValidation).As<ModelValidatorProvider>();
            //builder.RegisterType<AutofacValidatorFactory>().As<IValidatorFactory>().SingleInstance();
            // Register IValidator's
            FindAndRegisterValidators(builder);


            // Build: NO MORE REGISTRATION ALLOWED ABOVE
            _container = builder.Build();

            // Set MVC DependencyResolver to integrate
            DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
        }
Beispiel #26
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var typeFinder      = new AppDomainTypeFinder();
            var typesToRegister = typeFinder.FindClassesOfType(typeof(IEntityTypeConfiguration <>));

            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.ApplyConfiguration(configurationInstance);
            }
            base.OnModelCreating(modelBuilder);
        }
        public void TypeFinder_Benchmark_Findings()
        {
            var hostingEnvironment = new Mock <IHostingEnvironment>();

            hostingEnvironment.Setup(x => x.ContentRootPath).Returns(System.Reflection.Assembly.GetExecutingAssembly().Location);
            hostingEnvironment.Setup(x => x.WebRootPath).Returns(System.IO.Directory.GetCurrentDirectory());
            CommonHelper.DefaultFileProvider = new NopFileProvider(hostingEnvironment.Object);
            var finder = new AppDomainTypeFinder();
            var type   = finder.FindClassesOfType <ISomeInterface>().ToList();

            type.Count.ShouldEqual(1);
            typeof(ISomeInterface).IsAssignableFrom(type.FirstOrDefault()).ShouldBeTrue();
        }
Beispiel #28
0
        public void Benchmark_Findings()
        {
            var hostingEnvironment = new Mock <IHostingEnvironment>();

            hostingEnvironment.Setup(x => x.ContentRootPath).Returns(System.Reflection.Assembly.GetExecutingAssembly().Location);
            hostingEnvironment.Setup(x => x.WebRootPath).Returns(System.IO.Directory.GetCurrentDirectory());
            ICoreFileProvider coreFileProvider = new CoreFileProvider(hostingEnvironment.Object);
            var finder = new AppDomainTypeFinder(coreFileProvider);
            var type   = finder.FindClassesOfType <ITransientService>().ToList();

            Assert.Equal(4, type.Count);
            Assert.True(typeof(ITransientService).IsAssignableFrom(type.FirstOrDefault()));
        }
        /// <summary>
        /// 对单个插件进行状态监视
        /// </summary>
        /// <param name="pluginDir"></param>
        private static void ListenSinglePlugin(string pluginDir)
        {
            if (!Directory.Exists(pluginDir))
            {
                Logger.Info(string.Format("pluginDir  not Exists  {0} ", pluginDir));
                return;
            }

            string cacheBinFileFullPath  = Path.Combine(pluginDir, _load_plugins_completed_token);
            PostEvictionDelegate handler = null;

            handler = (key, valueNew, reason, state) =>
            {
                try
                {
                    Logger.Info(string.Format("plugin cache file {0} has changed and the plugins reload!", cacheBinFileFullPath));

                    //移除上次监视
                    ConfigHelper.MonitorConfingSnapshot.Remove(key);
                    //强制刷新当前插件,并进行下次的监视
                    var pluginFiles = new DirectoryInfo(pluginDir)
                                      .EnumerateFiles(PluginConstant.PluginFileNameFormat, SearchOption.TopDirectoryOnly);//查询插件格式的dll;
                    if (pluginFiles.IsNotEmpty())
                    {
                        foreach (var assFile in pluginFiles)
                        {
                            var ass            = Assembly.LoadFrom(assFile.FullName);
                            var typeFinder     = new AppDomainTypeFinder();
                            var lstPluginTypes = typeFinder.FindClassesOfType(_PluginType, new Assembly[] { ass }, true);
                            if (lstPluginTypes.IsNotEmpty())
                            {
                                foreach (var itemType in lstPluginTypes)
                                {
                                    try
                                    {
                                        CreatePluginInstance(itemType);
                                    }
                                    catch (Exception ex) { Logger.Error(ex); }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
            };
            //监控插件变更
            ListenFileChanged(cacheBinFileFullPath, handler);
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var typeFinder = new AppDomainTypeFinder();
            //dynamically load all entity and query type configurations
            var typeConfigurations = typeFinder.FindClassesOfType(typeof(NitaqatEntityTypeConfiguration <,>), true);

            foreach (var typeConfiguration in typeConfigurations)
            {
                var mappingConfiguration = (IMappingConfiguration)Activator.CreateInstance(typeConfiguration);
                mappingConfiguration.ApplyConfiguration(modelBuilder);
            }

            base.OnModelCreating(modelBuilder);
        }
Beispiel #31
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var typeFinder  = new AppDomainTypeFinder();
            var typeConfigs = typeFinder.FindClassesOfType(typeof(IEntityTypeConfiguration <>));

            foreach (var typeConfig in typeConfigs)
            {
                var instance = (IMapper)Activator.CreateInstance(typeConfig);
                instance.ApplyConfiguration(modelBuilder);
            }


            base.OnModelCreating(modelBuilder);
        }
Beispiel #32
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var typeFinder = new AppDomainTypeFinder();
            var typesToRegister = typeFinder.FindClassesOfType(typeof(IZergMapping), false)
                .Where(type => !String.IsNullOrEmpty(type.Namespace) && type.Namespace.StartsWith("Trading"))
                .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }

            base.BaseOnModelCreate(modelBuilder);
        }
Beispiel #33
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var typeFinder      = new AppDomainTypeFinder();
            var typesToRegister = typeFinder.FindClassesOfType(typeof(IZergMapping), false)
                                  .Where(type => !String.IsNullOrEmpty(type.Namespace) && type.Namespace.StartsWith("Trading"))
                                  .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration <>));

            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }

            base.BaseOnModelCreate(modelBuilder);
        }
Beispiel #34
0
        public static void AddTypeDescriptors()
        {
            var typeFinder = new AppDomainTypeFinder();
            var types      =
                typeFinder.FindClassesOfType <IBaseEntity>()
                .Where(x => x.GetCustomAttribute <MetadataTypeAttribute>() != null).ToList();

            types.AddRange(typeFinder.FindClassesOfType <BaseEntity>()
                           .Where(x => x.GetCustomAttribute <MetadataTypeAttribute>() != null));

            foreach (var type in types)
            {
                TypeDescriptor.AddProvider(new AssociatedMetadataTypeTypeDescriptionProvider(type), type);
            }
        }
        private static void RegisterConsumers(ContainerBuilder builder)
        {
            var typeFinder = new AppDomainTypeFinder();
            var types      = typeof(IConsumer <>);
            var consumers  = typeFinder.FindClassesOfType(types);

            foreach (var consumer in consumers)
            {
                builder.RegisterType(consumer)
                .As(consumer.FindInterfaces((type, criteria) =>
                                            type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition())
                                            , typeof(IConsumer <>)))
                .InstancePerHttpRequest();
            }
        }
Beispiel #36
0
        protected void Application_Start()
        {
            // Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DataContext>());
            //Database.SetInitializer<MemoryEntities>(null);
            //AreaRegistration.RegisterAllAreas();
            //RegisterGlobalFilters(GlobalFilters.Filters);

            //加载插件
            AppDomainTypeFinder typeFinder = new AppDomainTypeFinder();
            var embeddedViewResolver = new EmbeddedViewResolver(typeFinder);
            var embeddedProvider = new EmbeddedViewVirtualPathProvider(embeddedViewResolver.GetEmbeddedViews());
            HostingEnvironment.RegisterVirtualPathProvider(embeddedProvider);

            //群体注册服务,所有的继承IDependency接口的类都将被注册
            var builder = RegisterService();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            RegisterRoutes(RouteTable.Routes);
            AuthConfig.RegisterAuth();
        }