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(); }
public void Passes_FindClassesOfType_OnlyConcreteClassesFalse() { var types = _finder.FindClassesOfType(typeof(ISomeInterface), false); types.Count().TestEqual(4); types.Contains(typeof(AbstractSomeClass)).TestBeTrue(); types.Contains(typeof(SomeClass <>)).TestBeTrue(); types.Contains(typeof(SomeClass)).TestBeTrue(); types.Contains(typeof(SomeChildClass)).TestBeTrue(); }
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); } }
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); }); }
public static void RegisterRepositories <TDbContent>(this ContainerBuilder builder, Assembly assembly) where TDbContent : DbContext { var dbSetParam = new ResolvedParameter( (p, c) => { return(p.ParameterType == typeof(DbContext)); }, (p, c) => { return(c.Resolve <TDbContent>()); } ); var baseEntitys = typeFinder.FindClassesOfType <BaseEntity>(new[] { assembly }); foreach (var baseEntity in baseEntitys) { var entityIRepoType = iRepoType.MakeGenericType(baseEntity); var entityRepoType = efRepoType.MakeGenericType(baseEntity); builder .RegisterType(entityRepoType) .As(entityIRepoType) .WithParameter(dbSetParam) .InstancePerLifetimeScope(); } }
/// <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()); }
/// <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); }
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; }
//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; } } } }
/// <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 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); }
/// <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 } } }
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)); }
/// <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); }); } })); }
/// <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); }); } })); }
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 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); }
/// <summary> /// Delete database schema if it exists /// </summary> /// <param name="assembly">Assembly to find the mapping configurations classes; /// leave null to search mapping configurations classes on the whole application pull</param> public virtual void DeleteDatabaseSchemaIfExists(Assembly assembly = null) { //find database mapping configuration by other assemblies var typeFinder = new AppDomainTypeFinder(); var typeConfigurations = assembly != null ? typeFinder.FindClassesOfType <IMappingConfiguration>(new List <Assembly> { assembly }).ToList() : typeFinder.FindClassesOfType <IMappingConfiguration>().ToList(); //delete tables foreach (var mappingConfiguration in typeConfigurations) { (EngineContext.Current.ResolveUnregistered(mappingConfiguration) as IMappingConfiguration) ?.DeleteTableIfExists(); } }
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 FindAndRegisterValidators(ContainerBuilder builder) { var validators = _typeFinder.FindClassesOfType <IValidator>(); foreach (var type in validators) { builder.RegisterType(type).AsImplementedInterfaces().InstancePerLifetimeScope(); } }
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 Register(IServiceCollection services) { var typeFinder = new AppDomainTypeFinder(); var assemblies = typeFinder.GetAssemblies(); //Register myservice typeFinder.FindInterfacesOfType(typeof(IBaseService <>), assemblies) .ToList() .ForEach(x => { if (x != typeof(IBaseService <>)) { typeFinder.FindClassesOfType(x) .ToList() .ForEach(t => { services.AddScoped(x, t); }); } }); //Event services.AddScoped <ISubscriptionService, SubscriptionService>(); services.AddScoped <IEventPublisher, EventPublisher>(); //Register Consumers typeFinder.FindClassesOfType(typeof(IConsumer <>), assemblies) .ToList() .ForEach(x => { x.FindInterfaces((type, criteria) => { var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition()); return(isMatch); }, typeof(IConsumer <>)) .ToList() .ForEach(t => { services.AddScoped(t, x); }); }); }
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))); }
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); } }
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 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())); }
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(); }
/// <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(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); }
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); }
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); }
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); }
/// <summary> /// Create database schema if it not exists /// </summary> /// <param name="assembly">Assembly to find the mapping configurations classes; /// leave null to search mapping configurations classes on the whole application pull</param> public virtual void CreateDatabaseSchemaIfNotExists(Assembly assembly = null) { DataConnection.DefaultSettings = Singleton <DataSettings> .Instance; using (var currentConnection = new NopDataConnection()) { ConfigureDataContext(currentConnection); //find database mapping configuration by other assemblies var typeFinder = new AppDomainTypeFinder(); var typeConfigurations = assembly != null ? typeFinder.FindClassesOfType <IMappingConfiguration>(new List <Assembly> { assembly }).ToList() : typeFinder.FindClassesOfType <IMappingConfiguration>().ToList(); foreach (var typeConfiguration in typeConfigurations) { var mappingConfiguration = (IMappingConfiguration)Activator.CreateInstance(typeConfiguration); mappingConfiguration.CreateTableIfNotExists(currentConnection); } } }
private static void RegisterMappers(ContainerBuilder builder) { ITypeFinder typeFinder = new AppDomainTypeFinder(); var simpleMapperType = typeof(SimpleViewModelMapper <,>); var mapperType = typeof(IViewModelMapper <,>); var allConverterTypes = typeFinder.FindClassesOfType(mapperType).ToArray(); var allVmTypes = typeFinder.FindClassesOfType <BaseViewModel>().ToArray(); var allModelTypes = typeFinder.FindClassesOfType <BaseContent>().ToArray(); foreach (var vmType in allVmTypes) { var contentTypeName = vmType.Name.Replace("ViewModel", ""); var contentType = allModelTypes.FirstOrDefault( c => c.Name.Equals(contentTypeName, StringComparison.InvariantCultureIgnoreCase)); if (contentType == null) { continue; } var specificeMapperType = allConverterTypes.FirstOrDefault(ct => { var t = ct.GetInterfaces().First(i => i.GetGenericTypeDefinition() == mapperType); return(t.GenericTypeArguments[0] == contentType && t.GenericTypeArguments[1] == vmType); }); var concreteType = specificeMapperType ?? simpleMapperType.MakeGenericType(contentType, vmType); var target = mapperType.MakeGenericType(contentType, vmType); builder.RegisterType(concreteType).As(target).InstancePerHttpRequest(); AutoMapper.Mapper.CreateMap(contentType, vmType); } }
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(); } }