예제 #1
0
 /// <summary>
 /// Perform the bootstrapping of all configured services.
 /// </summary>
 /// <returns>Collection of generated notifications.</returns>
 public IEnumerable <BootstrapperNotification> Bootstrapp()
 {
     if (useMef)
     {
         using (var container = new ContainerConfiguration()
                                .WithParts(ReflectionTools.GetAllTypes())
                                .CreateContainer())
         {
             MEFServices = container.GetExports <IBootstrapperService>();
         }
     }
     BootstrappServices(useMef ? MEFServices : RegisteredServices);
     if (throwExceptionOnErrorNotif && notifications.Any(n => n.Type == BootstrapperNotificationType.Error))
     {
         throw new BootstrappingException(notifications);
     }
     if (OnPostBootstrapping != null)
     {
         OnPostBootstrapping(new PostBootstrappingContext
         {
             Notifications = notifications,
             Scope         = DIManager.IsInit ? DIManager.BeginScope() : null
         });
         OnPostBootstrapping = null; //Unsubscribe all
     }
     return(notifications.AsEnumerable());
 }
예제 #2
0
 /// <summary>
 /// Indicates to use all buses available within the system.
 /// </summary>
 /// <returns>Current configuration.</returns>
 public IEventDispatcherConfiguration UseAllAvailableBuses()
 {
     _busConfigs = ReflectionTools.GetAllTypes().Where(t => typeof(IDomainEventBus).IsAssignableFrom(t) && t.IsClass)
                   .Distinct(new TypeEqualityComparer())
                   .ToArray();
     return(this);
 }
예제 #3
0
        //Try get a replacement
        Type TryGetReplacement(string targetFullTypeName)
        {
            var allTypes = ReflectionTools.GetAllTypes();

            //Try find defined [DeserializeFrom] attribute
            foreach (var type in allTypes)
            {
                var att = type.RTGetAttribute <DeserializeFromAttribute>(false);
                if (att != null && att.previousTypeNames.Any(n => n == targetFullTypeName))
                {
                    return(type);
                }
            }

            //Try find type with same name in some other namespace that is subclass of Task
            var typeNameWithoutNS = targetFullTypeName.Split('.').LastOrDefault();

            foreach (var type in allTypes)
            {
                if (type.Name == typeNameWithoutNS && type.RTIsSubclassOf(typeof(NodeCanvas.Framework.Task)))
                {
                    return(type);
                }
            }

            return(null);
        }
예제 #4
0
        public void CoreDispatcherConfigurationBuilder_ForAllEvents_SingleBus_AsExpected()
        {
            var cfgBuilder = new DispatcherConfigurationBuilder();

            cfgBuilder
            .ForAllEvents()
            .UseBus <InMemoryEventBus>()
            .HandleErrorWith(e => _error = e.ToString())
            .SerializeWith <JsonDispatcherSerializer>();

            var cfg = cfgBuilder.Build();

            cfg.EventDispatchersConfiguration.Should().HaveCount(ReflectionTools.GetAllTypes()
                                                                 .Count(t => typeof(IDomainEvent).IsAssignableFrom(t) && t.IsClass));
            var dispatch = cfg.EventDispatchersConfiguration.First(t => t.EventType == typeof(TestDomainEvent));

            dispatch.Should().NotBeNull();
            dispatch.EventType.Should().Be(typeof(TestDomainEvent));
            dispatch.BusesTypes.Should().HaveCount(1);
            dispatch.ErrorHandler.Should().NotBeNull();
            dispatch.Serializer.Should().NotBeNull();

            var dispatcher = dispatch.BusesTypes.First();

            dispatcher.Should().Be(typeof(InMemoryEventBus));
        }
예제 #5
0
        public static Bootstrapper UseEFCoreAsMainRepository(this Bootstrapper bootstrapper, BaseDbContext dbContext,
                                                             EFCoreOptions options = null)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException(nameof(dbContext));
            }
            InitializeBootstrapperService(
                bootstrapper,
                (ctx) =>
            {
                if (ctx.IsServiceRegistered(BootstrapperServiceType.IoC))
                {
                    var entities = ReflectionTools.GetAllTypes()
                                   .Where(t => typeof(IPersistableEntity).IsAssignableFrom(t) &&
                                          !t.IsAbstract &&
                                          t.IsClass).ToList();
                    foreach (var item in entities)
                    {
                        var efRepoType         = typeof(EFRepository <>).MakeGenericType(item);
                        var dataReaderRepoType = typeof(IDataReaderRepository <>).MakeGenericType(item);
                        var databaseRepoType   = typeof(IDatabaseRepository <>).MakeGenericType(item);
                        var dataUpdateRepoType = typeof(IDataUpdateRepository <>).MakeGenericType(item);

                        bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(dbContext, dbContext.GetType()));

                        bootstrapper
                        .AddIoCRegistration(new FactoryRegistration(() => efRepoType.CreateInstance(dbContext),
                                                                    efRepoType, dataUpdateRepoType, databaseRepoType, dataReaderRepoType));
                    }
                }
            },
                options);
            return(bootstrapper);
        }
예제 #6
0
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull)
            {
                return;
            }

            var json = data.AsDictionary;

            fsData typeData;

            if (json.TryGetValue("$type", out typeData))
            {
                var serializedType = ReflectionTools.GetType(typeData.AsString);

                if (serializedType == null || serializedType == typeof(MissingConnection))
                {
                    //TargetType is either the one missing or the one previously stored as missing in the MissingConnection.
                    var targetFullTypeName = serializedType == null? typeData.AsString : json["missingType"].AsString;
                    //Try find type with same name in some other namespace that is subclass of Connection
                    var typeNameWithoutNS = targetFullTypeName.Split('.').LastOrDefault();
                    foreach (var type in ReflectionTools.GetAllTypes())
                    {
                        if (type.Name == typeNameWithoutNS && type.IsSubclassOf(typeof(NodeCanvas.Framework.Connection)))
                        {
                            json["$type"] = new fsData(type.FullName);
                            return;
                        }
                    }
                }

                //Handle missing serialized Connection type
                if (serializedType == null)
                {
                    //inject the 'MissingConnection' type and store recovery serialization state.
                    //recoveryState and missingType are serializable members of MissingConnection.
                    json["recoveryState"] = new fsData(data.ToString());
                    json["missingType"]   = new fsData(typeData.AsString);
                    json["$type"]         = new fsData(typeof(MissingConnection).FullName);
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingConnection))
                {
                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType(json["missingType"].AsString);
                    if (missingType != null)
                    {
                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson   = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json          = json.Concat(recoverJson.Where(kvp => !json.ContainsKey(kvp.Key))).ToDictionary(c => c.Key, c => c.Value);
                        json["$type"] = new fsData(missingType.FullName);
                        data          = new fsData(json);
                    }
                }
            }
        }
예제 #7
0
        private void DoSearch()
        {
            searchTypeList = new List <Type>();
            var types = ReflectionTools.GetAllTypes(false).Where((t) => {
                var att = t.RTGetAttribute <QuickExecuteAttribute>(false);
                return(att != null && att.CanSearch);
            });

            searchTypeList = types.ToList();
        }
        /// <summary>
        /// Gets a configuration to apply to all commands that were not configured yet.
        /// </summary>
        /// <returns>Mutilple command type configuration</returns>
        public MultipleCommandTypeConfiguration ForAllOtherCommands()
        {
            var eventTypes = ReflectionTools.GetAllTypes()
                             .Where(IsCommandTypeAndNotAlreadyDefined);

            if (eventTypes.Any())
            {
                return(ForCommands(eventTypes.ToArray()));
            }
            return(new MultipleCommandTypeConfiguration());
        }
예제 #9
0
 /// <summary>
 /// <para>
 /// Do a strict validation upon the configuration.
 /// It means that every events need to be dispatched in at least one bus.
 /// </para>
 /// <para>
 /// If the configuration was not build with the strict flag, this will returns true in all cases.
 /// </para>
 /// </summary>
 /// <returns>True if the configuration is stricly valid, false otherwise.</returns>
 public bool ValidateStrict()
 {
     if (_strict)
     {
         var typeComparer = new TypeEqualityComparer();
         var allTypes     = ReflectionTools.GetAllTypes().Where(t =>
                                                                (typeof(IDomainEvent).IsAssignableFrom(t) || typeof(ICommand).IsAssignableFrom(t)) && t.IsClass).ToList();
         return(allTypes.All(t =>
                             EventDispatchersConfiguration.Any(cfg => cfg.BusesTypes.WhereNotNull().Any())));
     }
     return(true);
 }
예제 #10
0
        private Type GetFocusFileType(string name)
        {
            var types = ReflectionTools.GetAllTypes(false).Where((t) => {
                var att = t.RTGetAttribute <QuickExecuteAttribute>(false);
                return(att != null && att.CanSearch && t.Name.Equals(name));
            });

            if (types.Count() < 1)
            {
                return(null);
            }
            return(types.ToArray()[0]);
        }
예제 #11
0
        public static Bootstrapper UseMongoDbAsMainRepository(this Bootstrapper bootstrapper, MongoDbOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var service = new MongoDbDALBootstrapperService
            {
                BootstrappAction = (ctx) =>
                {
                    if (BsonSerializer.SerializerRegistry.GetSerializer <Type>() == null)
                    {
                        BsonSerializer.RegisterSerializer(typeof(Type), new TypeSerializer());
                    }
                    if (BsonSerializer.SerializerRegistry.GetSerializer <Guid>() == null)
                    {
                        BsonSerializer.RegisterSerializer(typeof(Guid), new GuidSerializer());
                    }
                    MongoDbContext.DatabaseName = options.DatabaseName;
                    MongoDbContext.MongoClient  = new MongoDB.Driver.MongoClient(options.Url);

                    var pack = new ConventionPack();
                    pack.Add(new IgnoreExtraElementsConvention(true));
                    ConventionRegistry.Register("CQELight conventions", pack, _ => true);

                    if (ctx.IsServiceRegistered(BootstrapperServiceType.IoC))
                    {
                        bootstrapper.AddIoCRegistration(new TypeRegistration <MongoDataReaderAdapter>(true));
                        bootstrapper.AddIoCRegistration(new TypeRegistration <MongoDataWriterAdapter>(true));

                        var entities = ReflectionTools.GetAllTypes()
                                       .Where(t => typeof(IPersistableEntity).IsAssignableFrom(t)).ToList();
                        foreach (var item in entities)
                        {
                            var mongoRepoType      = typeof(MongoRepository <>).MakeGenericType(item);
                            var dataReaderRepoType = typeof(IDataReaderRepository <>).MakeGenericType(item);
                            var databaseRepoType   = typeof(IDatabaseRepository <>).MakeGenericType(item);
                            var dataUpdateRepoType = typeof(IDataUpdateRepository <>).MakeGenericType(item);

                            bootstrapper
                            .AddIoCRegistration(new FactoryRegistration(() => mongoRepoType.CreateInstance(),
                                                                        mongoRepoType, dataUpdateRepoType, databaseRepoType, dataReaderRepoType));
                        }
                    }
                }
            };

            bootstrapper.AddService(service);
            return(bootstrapper);
        }
예제 #12
0
        Type TryGetReplacement(string targetFullTypeName)
        {
            var typeNameWithoutNS = targetFullTypeName.Split('.').LastOrDefault();

            foreach (var type in ReflectionTools.GetAllTypes())
            {
                if (type.Name == typeNameWithoutNS && type.RTIsSubclassOf(typeof(NodeCanvas.Framework.Connection)))
                {
                    return(type);
                }
            }

            return(null);
        }
예제 #13
0
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            foreach (var type in ReflectionTools.GetAllTypes(excludedAutoRegisterTypeDlls)
                     .Where(t =>
                            (t.ImplementsRawGenericInterface(typeof(ICommandHandler <>)) || t.ImplementsRawGenericInterface(typeof(IDomainEventHandler <>))) && t.IsClass && !t.IsAbstract).ToList())
            {
                var registration = builder.RegisterType(type)
                                   .IfNotRegistered(type)
                                   .AsImplementedInterfaces()
                                   .AsSelf();
                if (!type.IsDefined(typeof(DefineTypeResolutionModeAttribute)) ||
                    type.GetCustomAttribute <DefineTypeResolutionModeAttribute>()?.Mode == TypeResolutionMode.Full)
                {
                    registration.FindConstructorsWith(new FullConstructorFinder());
                }
            }

            foreach (var type in ReflectionTools.GetAllTypes(excludedAutoRegisterTypeDlls)
                     .Where(t => typeof(IAutoRegisterType).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract).ToList())
            {
                var registration = builder.RegisterType(type)
                                   .IfNotRegistered(type)
                                   .AsImplementedInterfaces()
                                   .AsSelf();
                if (!type.IsDefined(typeof(DefineTypeResolutionModeAttribute)) ||
                    type.GetCustomAttribute <DefineTypeResolutionModeAttribute>()?.Mode == TypeResolutionMode.Full)
                {
                    registration.FindConstructorsWith(new FullConstructorFinder());
                }
            }

            foreach (var type in ReflectionTools.GetAllTypes(excludedAutoRegisterTypeDlls)
                     .Where(t => typeof(IAutoRegisterTypeSingleInstance).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract).ToList())
            {
                var registration = builder.RegisterType(type)
                                   .IfNotRegistered(type)
                                   .AsImplementedInterfaces()
                                   .AsSelf()
                                   .SingleInstance();
                if (!type.IsDefined(typeof(DefineTypeResolutionModeAttribute)) ||
                    type.GetCustomAttribute <DefineTypeResolutionModeAttribute>()?.Mode == TypeResolutionMode.Full)
                {
                    registration.FindConstructorsWith(new FullConstructorFinder());
                }
            }
        }
예제 #14
0
        /// <summary>
        /// Base constructor for event bus configuration.
        /// </summary>
        /// <param name="eventsLifetime">Definition of events life time. If null, default
        /// is applied, which means that every event type has a lifetime of 1 day.</param>
        /// <param name="parallelDispatchEventTypes">Collection of type of events
        /// that allows parallelDispatch.</param>
        public BaseEventBusConfiguration(IEnumerable <EventLifeTimeConfiguration> eventsLifetime, IEnumerable <Type> parallelDispatchEventTypes)
        {
            if (eventsLifetime != null)
            {
                EventsLifetime = eventsLifetime;
            }
            else
            {
                EventsLifetime = ReflectionTools.GetAllTypes()
                                 .Where(t => typeof(IDomainEvent).IsAssignableFrom(t))
                                 .Select(t => new
                                         EventLifeTimeConfiguration(t, TimeSpan.FromDays(1)));
            }

            _parallelDispatchEventTypes = (parallelDispatchEventTypes ?? Enumerable.Empty <Type>()).ToList();
        }
예제 #15
0
        //Returns whether there is a CustomObjectWrapper implemented for target type
        static System.Type[] FindCustomObjectWrappers(System.Type targetType)
        {
            var results = new List <System.Type>();

            foreach (var type in ReflectionTools.GetAllTypes())
            {
                if (type.IsSubclassOf(typeof(CustomObjectWrapper)))
                {
                    var args = type.BaseType.GetGenericArguments();
                    if (args.Length == 1 && args[0] == targetType)
                    {
                        results.Add(type);
                    }
                }
            }
            return(results.ToArray());
        }
예제 #16
0
        public static Type GetExtractorType(Type type)
        {
            if (_extractors == null)
            {
                _extractors = new Dictionary <Type, Type>();
                var extractorTypes = ReflectionTools.GetAllTypes().Where(t => !t.IsGenericTypeDefinition && !t.IsAbstract && t.RTIsSubclassOf(typeof(ExtractorNode)));
                foreach (var extractorType in extractorTypes)
                {
                    var invokeMethod = extractorType.RTGetMethod("Invoke");
                    var targetType   = invokeMethod.GetParameters()[0].ParameterType;
                    _extractors[targetType] = extractorType;
                }
            }
            Type result = null;

            _extractors.TryGetValue(type, out result);
            return(result);
        }
예제 #17
0
        private static void AddAutoRegisteredTypes(Bootstrapper bootstrapper, IServiceCollection services, string[] excludedDllsForAutoRegistration)
        {
            bool CheckPublicConstructorAvailability(Type type)
            {
                if (type.GetConstructors().Any(c => c.IsPublic))
                {
                    return(true);
                }
                bootstrapper.AddNotification(new BootstrapperNotification(BootstrapperNotificationType.Error, "You must provide public constructor to Microsoft.Extensions.DependencyInjection extension cause it only supports public constructor. If you want to use internal or private constructor, switch to another IoC provider that supports this feature."));
                return(false);
            }

            foreach (var type in ReflectionTools.GetAllTypes(excludedDllsForAutoRegistration)
                     .Where(t => typeof(IAutoRegisterType).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract).ToList())
            {
                if (!CheckPublicConstructorAvailability(type))
                {
                    continue;
                }

                services.AddTransient(type, type);
                foreach (var @interface in type.GetInterfaces())
                {
                    services.AddTransient(@interface, type);
                }
            }

            foreach (var type in ReflectionTools.GetAllTypes(excludedDllsForAutoRegistration)
                     .Where(t => typeof(IAutoRegisterTypeSingleInstance).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract).ToList())
            {
                if (!CheckPublicConstructorAvailability(type))
                {
                    continue;
                }

                services.AddSingleton(type, type);
                foreach (var @interface in type.GetInterfaces())
                {
                    services.AddSingleton(@interface, type);
                }
            }
        }
예제 #18
0
        public static Bootstrapper UseMongoDbAsMainRepository(this Bootstrapper bootstrapper, MongoDbOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var service = new MongoDbDALBootstrapperService
                              (ctx =>
            {
                InitiMongoDbStaticStuff();
                MongoDbContext.DatabaseName = options.DatabaseName;
                MongoDbContext.MongoClient  = new MongoDB.Driver.MongoClient(options.Url);

                if (ctx.IsServiceRegistered(BootstrapperServiceType.IoC))
                {
                    bootstrapper.AddIoCRegistration(new TypeRegistration <MongoDataReaderAdapter>(true));
                    bootstrapper.AddIoCRegistration(new TypeRegistration <MongoDataWriterAdapter>(true));

                    bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(MongoDbContext.MongoClient, RegistrationLifetime.Singleton, typeof(MongoClient)));

                    var entities = ReflectionTools.GetAllTypes()
                                   .Where(t => typeof(IPersistableEntity).IsAssignableFrom(t)).ToList();
                    foreach (var item in entities)
                    {
                        var mongoRepoType      = typeof(MongoRepository <>).MakeGenericType(item);
                        var dataReaderRepoType = typeof(IDataReaderRepository <>).MakeGenericType(item);
                        var databaseRepoType   = typeof(IDatabaseRepository <>).MakeGenericType(item);
                        var dataUpdateRepoType = typeof(IDataUpdateRepository <>).MakeGenericType(item);

                        bootstrapper
                        .AddIoCRegistration(new FactoryRegistration(() => mongoRepoType.CreateInstance(),
                                                                    mongoRepoType, dataUpdateRepoType, databaseRepoType, dataReaderRepoType));
                    }
                }
            }
                              );

            bootstrapper.AddService(service);
            return(bootstrapper);
        }
예제 #19
0
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            foreach (var type in ReflectionTools.GetAllTypes(_excludedAutoRegisterTypeDlls)
                     .Where(t =>
                            (t.ImplementsRawGenericInterface(typeof(ICommandHandler <>)) || t.ImplementsRawGenericInterface(typeof(IDomainEventHandler <>))) && t.IsClass && !t.IsAbstract).ToList())
            {
                builder.RegisterType(type)
                .IfNotRegistered(type)
                .AsImplementedInterfaces()
                .AsSelf()
                .FindConstructorsWith(new FullConstructorFinder());
            }

            foreach (var type in ReflectionTools.GetAllTypes(_excludedAutoRegisterTypeDlls)
                     .Where(t => typeof(IAutoRegisterType).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract).ToList())
            {
                builder.RegisterType(type)
                .IfNotRegistered(type)
                .AsImplementedInterfaces()
                .AsSelf()
                .FindConstructorsWith(new FullConstructorFinder());
            }

            foreach (var type in ReflectionTools.GetAllTypes(_excludedAutoRegisterTypeDlls)
                     .Where(t => typeof(IAutoRegisterTypeSingleInstance).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract).ToList())
            {
                builder.RegisterType(type)
                .IfNotRegistered(type)
                .AsImplementedInterfaces()
                .AsSelf()
                .SingleInstance()
                .FindConstructorsWith(new FullConstructorFinder());
            }
        }
예제 #20
0
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull)
            {
                return;
            }

            var json = data.AsDictionary;

            fsData typeData;

            if (json.TryGetValue("$type", out typeData))
            {
                var serializedType = ReflectionTools.GetType(typeData.AsString);

                if (serializedType == null || serializedType == typeof(MissingAction) || serializedType == typeof(MissingCondition))
                {
                    //TargetType is either the one missing or the one previously stored as missing in the MissingTask.
                    var targetFullTypeName = serializedType == null? typeData.AsString : json["missingType"].AsString;
                    //try find defined [DeserializeFrom] attribute
                    foreach (var type in ReflectionTools.GetAllTypes())
                    {
                        var att = type.RTGetAttribute <DeserializeFromAttribute>(false);
                        if (att != null && att.previousTypeNames.Any(n => n == targetFullTypeName))
                        {
                            json["$type"] = new fsData(type.FullName);
                            return;
                        }
                    }

                    //Try find type with same name in some other namespace that is subclass of Task
                    var typeNameWithoutNS = targetFullTypeName.Split('.').LastOrDefault();
                    foreach (var type in ReflectionTools.GetAllTypes())
                    {
                        if (type.Name == typeNameWithoutNS && type.IsSubclassOf(typeof(NodeCanvas.Framework.Task)))
                        {
                            json["$type"] = new fsData(type.FullName);
                            return;
                        }
                    }
                }

                //Handle missing serialized Task type
                if (serializedType == null)
                {
                    //Otherwise replace with a missing task.
                    Type missingNodeType = null;
                    if (storageType == typeof(ActionTask))
                    {
                        missingNodeType = typeof(MissingAction);
                    }
                    if (storageType == typeof(ConditionTask))
                    {
                        missingNodeType = typeof(MissingCondition);
                    }
                    if (missingNodeType == null)
                    {
                        return;
                    }

                    //inject the 'MissingTask' type and store recovery serialization state.
                    //recoveryState and missingType are serializable members of MissingTask.
                    json["$type"]         = new fsData(missingNodeType.FullName);
                    json["recoveryState"] = new fsData(data.ToString());
                    json["missingType"]   = new fsData(typeData.AsString);

                    //There is no way to know DecalredOnly properties to save just them instead of the whole object since we dont have an actual type
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingAction) || serializedType == typeof(MissingCondition))
                {
                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType(json["missingType"].AsString);
                    if (missingType != null)
                    {
                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson   = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json          = json.Concat(recoverJson.Where(kvp => !json.ContainsKey(kvp.Key))).ToDictionary(c => c.Key, c => c.Value);
                        json["$type"] = new fsData(missingType.FullName);
                        data          = new fsData(json);
                    }
                }
            }
        }
 /// <summary>
 /// Gets a configuration to apply to all events of the app.
 /// </summary>
 /// <returns>Mutilple event type configuration</returns>
 public MultipleEventTypeConfiguration ForAllEvents()
 => ForEvents(ReflectionTools.GetAllTypes()
              .Where(t => typeof(IDomainEvent).IsAssignableFrom(t) && t.IsClass).ToArray());
 /// <summary>
 /// Gets a configuration to apply to all commands of the app.
 /// </summary>
 /// <returns>Mutilple command type configuration</returns>
 public MultipleCommandTypeConfiguration ForAllCommands()
 => ForCommands(ReflectionTools.GetAllTypes()
                .Where(t => typeof(ICommand).IsAssignableFrom(t) && t.IsClass).ToArray());
예제 #23
0
 internal static void InitHandlersCollection(params string[] excludedDLLs)
 {
     _handlers = ReflectionTools.GetAllTypes(excludedDLLs)
                 .Where(IsCommandHandler).ToList();
 }
예제 #24
0
        /// <summary>
        /// Configure EF Core as repository implementation.
        /// This methods uses a single database configuration and create dynamically all context
        /// from every concerned assembly.
        /// </summary>
        /// <param name="bootstrapper">Bootstrapper instance</param>
        /// <param name="optionsBuilderCfg">Options builder configuration lambda.</param>
        /// <param name="options">Custom options to use of using EF.</param>
        public static Bootstrapper UseEFCoreAsMainRepository(this Bootstrapper bootstrapper, Action <DbContextOptionsBuilder> optionsBuilderCfg,
                                                             EFCoreOptions options = null)
        {
            if (optionsBuilderCfg == null)
            {
                throw new ArgumentNullException(nameof(optionsBuilderCfg));
            }

            InitializeBootstrapperService(
                bootstrapper,
                (ctx) =>
            {
                if (ctx.IsServiceRegistered(BootstrapperServiceType.IoC))
                {
                    var dbContextOptionsBuilder = new DbContextOptionsBuilder();
                    optionsBuilderCfg(dbContextOptionsBuilder);
                    foreach (var item in ReflectionTools.GetAllTypes().Where(t => t.IsSubclassOf(typeof(BasePersistableEntity)) && !t.IsAbstract && t.IsClass).ToList())
                    {
                        var efRepoType         = typeof(EFRepository <>).MakeGenericType(item);
                        var dataReaderRepoType = typeof(IDataReaderRepository <>).MakeGenericType(item);
                        var databaseRepoType   = typeof(IDatabaseRepository <>).MakeGenericType(item);
                        var dataUpdateRepoType = typeof(IDataUpdateRepository <>).MakeGenericType(item);

                        Type ctxType = null;

                        if (s_ContextTypesPerAssembly.ContainsKey(item.Assembly.FullName))
                        {
                            ctxType = s_ContextTypesPerAssembly[item.Assembly.FullName];
                        }
                        else
                        {
                            ctxType = ReflectionTools
                                      .GetAllTypes()
                                      .Where(t => t.Assembly.FullName == item.Assembly.FullName)
                                      .FirstOrDefault(c => c.IsSubclassOf(typeof(BaseDbContext)));
                            s_ContextTypesPerAssembly[item.Assembly.FullName] = ctxType;
                        }

                        if (ctxType == null)
                        {
                            throw new InvalidOperationException("Bootstrapper.UseEFCoreAsMainRepository() : " +
                                                                $"No DbContext found for assembly {item.Assembly.FullName}, but this assembly contains a " +
                                                                "some persistence entities. You need to create a specific class that inherits from BaseDbContext in this assembly to use this configuration method.");
                        }


                        bootstrapper
                        .AddIoCRegistration(new FactoryRegistration(() => ctxType.CreateInstance(dbContextOptionsBuilder.Options), ctxType));

                        bootstrapper
                        .AddIoCRegistration(new FactoryRegistration(() =>
                        {
                            var dbCtx = ctxType.CreateInstance(dbContextOptionsBuilder.Options);
                            return(efRepoType.CreateInstance(dbCtx));
                        },
                                                                    efRepoType, dataUpdateRepoType, databaseRepoType, dataReaderRepoType));
                    }
                }
            }, options);
            return(bootstrapper);
        }
 //...
 void OnEnable()
 {
     titleContent = new GUIContent("Preferred Types");
     typeList     = UserTypePrefs.GetPreferedTypesList();
     alltypes     = ReflectionTools.GetAllTypes(true).Where(t => !t.IsGenericType && !t.IsGenericTypeDefinition).ToList();
 }
예제 #26
0
        /// <summary>
        /// Configure EF Core as repository implementation.
        /// This methods uses a single database configuration and create dynamically all context
        /// from every concerned assembly.
        /// </summary>
        /// <param name="bootstrapper">Bootstrapper instance</param>
        /// <param name="optionsBuilderCfg">Options builder configuration lambda.</param>
        /// <param name="options">Custom options to use of using EF.</param>
        public static Bootstrapper UseEFCoreAsMainRepository(this Bootstrapper bootstrapper, Action <DbContextOptionsBuilder> optionsBuilderCfg,
                                                             EFCoreOptions options = null)
        {
            if (optionsBuilderCfg == null)
            {
                throw new ArgumentNullException(nameof(optionsBuilderCfg));
            }

            InitializeBootstrapperService(
                bootstrapper,
                (ctx) =>
            {
                if (ctx.IsServiceRegistered(BootstrapperServiceType.IoC))
                {
                    var dbContextOptionsBuilder = new DbContextOptionsBuilder();
                    optionsBuilderCfg(dbContextOptionsBuilder);


                    var customDbContexts = ReflectionTools.GetAllTypes().Where(t => t.IsInHierarchySubClassOf(typeof(BaseDbContext)) && !t.IsAbstract && t.IsClass && t != typeof(BaseDbContext));
                    if (customDbContexts.Any())
                    {
                        foreach (var customDbContextType in customDbContexts)
                        {
                            bootstrapper.AddIoCRegistration(new TypeRegistration(customDbContextType, true));
                            var customDbContextOptionsType = typeof(DbContextOptions <>).MakeGenericType(customDbContextType);
                            bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(dbContextOptionsBuilder.Options, typeof(DbContextOptions), customDbContextOptionsType));
                            bootstrapper.AddIoCRegistration(new FactoryRegistration((scope) =>
                            {
                                return(new EFCoreDataReaderAdapter(scope.Resolve(customDbContextType) as BaseDbContext, options));
                            },
                                                                                    typeof(EFCoreDataReaderAdapter),
                                                                                    typeof(IDataReaderAdapter)));
                            bootstrapper.AddIoCRegistration(new FactoryRegistration((scope) =>
                            {
                                return(new EFCoreDataWriterAdapter(scope.Resolve(customDbContextType) as BaseDbContext, options));
                            },
                                                                                    typeof(EFCoreDataWriterAdapter),
                                                                                    typeof(IDataWriterAdapter)));
                        }
                    }
                    else
                    {
                        bootstrapper.AddIoCRegistration(new TypeRegistration(typeof(BaseDbContext), typeof(BaseDbContext)));
                        bootstrapper.AddIoCRegistration(new TypeRegistration <EFCoreDataReaderAdapter>(true));
                        bootstrapper.AddIoCRegistration(new TypeRegistration <EFCoreDataWriterAdapter>(true));
                        bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(dbContextOptionsBuilder.Options, typeof(DbContextOptions), typeof(DbContextOptions <BaseDbContext>)));
                    }

                    if (options != null)
                    {
                        bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(options, typeof(EFCoreOptions)));
                    }


                    foreach (var item in ReflectionTools.GetAllTypes().Where(t => typeof(IPersistableEntity).IsAssignableFrom(t) && !t.IsAbstract && t.IsClass).ToList())
                    {
                        var efRepoType         = typeof(EFRepository <>).MakeGenericType(item);
                        var dataReaderRepoType = typeof(IDataReaderRepository <>).MakeGenericType(item);
                        var databaseRepoType   = typeof(IDatabaseRepository <>).MakeGenericType(item);
                        var dataUpdateRepoType = typeof(IDataUpdateRepository <>).MakeGenericType(item);

                        Type ctxType = null;

                        if (s_ContextTypesPerAssembly.ContainsKey(item.Assembly.FullName))
                        {
                            ctxType = s_ContextTypesPerAssembly[item.Assembly.FullName];
                        }
                        else
                        {
                            ctxType = ReflectionTools
                                      .GetAllTypes()
                                      .Where(t => t.Assembly.FullName == item.Assembly.FullName)
                                      .FirstOrDefault(c => c.IsSubclassOf(typeof(BaseDbContext)));
                            s_ContextTypesPerAssembly[item.Assembly.FullName] = ctxType;

                            bootstrapper
                            .AddIoCRegistration(new FactoryRegistration(() => ctxType.CreateInstance(dbContextOptionsBuilder.Options), ctxType));
                        }

                        if (ctxType == null)
                        {
                            throw new InvalidOperationException("Bootstrapper.UseEFCoreAsMainRepository() : " +
                                                                $"No DbContext found for assembly {item.Assembly.FullName}, but this assembly contains a " +
                                                                "some persistence entities. You need to create a specific class that inherits from BaseDbContext in this assembly to use this configuration method.");
                        }

                        bootstrapper
                        .AddIoCRegistration(new FactoryRegistration(() =>
                        {
                            var dbCtx = ctxType.CreateInstance(dbContextOptionsBuilder.Options);
                            return(efRepoType.CreateInstance(dbCtx));
                        },
                                                                    efRepoType, dataUpdateRepoType, databaseRepoType, dataReaderRepoType));
                    }
                }
                else
                {
                    bootstrapper.AddNotification(new Bootstrapping.Notifications.BootstrapperNotification(Bootstrapping.Notifications.BootstrapperNotificationType.Warning,
                                                                                                          "No IoC has been configured in your system, it means that all EF DAL will no works 'automatically'," +
                                                                                                          " you will need to use it with EFCoreDataReaderAdapter and EFCoreDataWriterAdapter with the RepositoryBase class. " +
                                                                                                          "While this will work, it's not a recommended option and configuring IoC should be strongly considered."));
                }
            }, options);
            return(bootstrapper);
        }
예제 #27
0
 internal static void InitHandlersCollection(string[] excludedDLLs)
 {
     s_eventHandlers ??= ReflectionTools.GetAllTypes(excludedDLLs).Where(IsEventHandler).WhereNotNull().ToList();
 }
예제 #28
0
        ///Generates AOT classes file out of preferred types list
        public static void GenerateAOTClasses(string path, Type[] targetTypes)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            var spoofTypes = defaultSpoofTypes;

            spoofTypes.AddRange(targetTypes.Where(t => t.IsValueType && !spoofTypes.Contains(t)));
            spoofTypes = spoofTypes.Distinct().ToList();
            var types = ReflectionTools.GetAllTypes(true).Where(t => t.RTIsDefined(typeof(SpoofAOTAttribute), true)).Distinct();

            var nTypes   = 0;
            var nMethods = 0;

            var sb = new StringBuilder();

            sb.AppendLine("#pragma warning disable 0219, 0168, 0612");
            sb.AppendLine("namespace ParadoxNotion.Internal{");
            sb.AppendLine();
            sb.AppendLine("\t//Auto generated classes for AOT support, where using undeclared generic classes with value types is limited. These are not actualy used but rather just declared for the compiler");
            sb.AppendLine("\tpartial class AOTDummy{");
            sb.AppendLine();
            sb.AppendLine("\t\tobject o = null;");

            sb.AppendLine("\t\t///----------------------------------------------------------------------------------------------");

            //Generic Types
            foreach (var type in types)
            {
                if (!type.IsAbstract && type.IsGenericTypeDefinition && type.RTGetGenericArguments().Length == 1)
                {
                    var constrains = type.RTGetGenericArguments()[0].GetGenericParameterConstraints();

                    if (constrains.Length == 0 || constrains[0].IsValueType)
                    {
                        if (typeof(Delegate).IsAssignableFrom(type))
                        {
                            nTypes++;
                            sb.AppendLine(string.Format("\t\tvoid {0}()", type.FriendlyName(true).Replace(".", "_").Replace("<T>", "_Delegate")) + "{");
                            foreach (var spoofType in spoofTypes)
                            {
                                var a = type.FriendlyName(true).Replace("<T>", "<" + spoofType.FullName + ">").Replace("+", ".");
                                var b = "_" + type.FriendlyName(true).Replace(".", "_").Replace("<T>", "_" + spoofType.FullName.Replace(".", "_").Replace("+", "_"));
                                sb.AppendLine(string.Format("\t\t\t{0} {1};", a, b));
                            }
                            sb.AppendLine("\t\t}");
                        }
                        else
                        {
                            foreach (var spoofType in spoofTypes)
                            {
                                nTypes++;
                                var a = type.FriendlyName(true).Replace("<T>", "<" + spoofType.FullName + ">").Replace("+", ".");
                                var b = type.FriendlyName(true).Replace(".", "_").Replace("<T>", "_" + spoofType.FullName.Replace(".", "_").Replace("+", "_"));
                                sb.AppendLine(string.Format("\t\t{0} {1};", a, b));
                            }
                        }

                        sb.AppendLine();
                    }
                }
            }

            sb.AppendLine("\t\t///----------------------------------------------------------------------------------------------");

            //Generic Methods
            foreach (var type in types)
            {
                var index = 0;
                foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly))
                {
                    if (method.IsObsolete())
                    {
                        continue;
                    }

                    if (method.IsGenericMethodDefinition && method.RTGetGenericArguments().Length == 1)
                    {
                        var constrains = method.RTGetGenericArguments()[0].GetGenericParameterConstraints();

                        if (constrains.Length == 0 || constrains[0].IsValueType)
                        {
                            index++;

                            var decType = method.DeclaringType;
                            var varName = "_" + decType.FullName.Replace(".", "_");
                            sb.AppendLine(string.Format("\t\tvoid {0}_{1}_{2}()", decType.FullName.Replace(".", "_"), method.Name, index) + " {");
                            if (!method.IsStatic)
                            {
                                sb.AppendLine(string.Format("\t\t\t{0} {1} = default({2});", decType.FullName, varName, decType.FullName));
                            }

                            foreach (var spoofType in spoofTypes)
                            {
                                nMethods++;
                                var a            = method.IsStatic ? decType.FullName : varName;
                                var b            = method.Name;
                                var c            = spoofType.FullName.Replace("+", ".");
                                var paramsString = "";
                                var parameters   = method.GetParameters();
                                for (var i = 0; i < parameters.Length; i++)
                                {
                                    var parameter = parameters[i];
                                    var toString  = parameter.ParameterType.FullName;
                                    if (parameter.ParameterType.IsGenericParameter)
                                    {
                                        toString = spoofType.FullName;
                                    }
                                    if (parameter.ParameterType.IsGenericType)
                                    {
                                        toString = parameter.ParameterType.FriendlyName(true).Replace("<T>", "<" + spoofType.FullName + ">");
                                        toString = toString.Replace("[[T]]", "");
                                    }
                                    toString      = toString.Replace("+", ".");
                                    paramsString += string.Format("({0})o", toString);
                                    if (i < parameters.Length - 1)
                                    {
                                        paramsString += ", ";
                                    }
                                }
                                var d = paramsString;
                                sb.AppendLine(string.Format("\t\t\t{0}.{1}<{2}>( {3} );", a, b, c, d));
                            }

                            sb.AppendLine("\t\t}");
                            sb.AppendLine();
                        }
                    }
                }
            }

            sb.AppendLine("\t\t///----------------------------------------------------------------------------------------------");

            //custom stuff
            sb.AppendLine("\t\tvoid CustomSpoof(){");
            foreach (var spoofType in spoofTypes)
            {
                var sName = spoofType.FullName.Replace("+", ".");
                var fName = spoofType.FullName.Replace(".", "_").Replace("+", "_");
                foreach (var genericType in customGenericSpoof)
                {
                    nTypes++;
                    var a = genericType.FriendlyName(true).Replace("<T>", "<" + sName + ">");
                    var b = genericType.FriendlyName(true).Replace(".", "_").Replace("<T>", "_") + fName;
                    sb.AppendLine(string.Format("\t\t\t{0} {1};", a, b));
                }
                nTypes++;
                sb.AppendLine(string.Format("\t\t\tSystem.Collections.Generic.IDictionary<System.String, {0}> IDict_{1};", sName, fName));
                sb.AppendLine(string.Format("\t\t\tSystem.Collections.Generic.Dictionary<System.String, {0}> Dict_{1};", sName, fName));
                sb.AppendLine("\t\t\t///------");
            }
            sb.AppendLine("\t\t}");
            sb.AppendLine("\t}");
            sb.AppendLine("}");
            sb.AppendLine();
            sb.AppendLine(string.Format("//{0} Types | {1} Methods spoofed", nTypes, nMethods));
            sb.AppendLine("#pragma warning restore 0219, 0168, 0612");

            File.WriteAllText(path, sb.ToString());
        }