Example #1
0
        public static void AddRepositoriesPattern(this IServiceCollection services, Action <DataFwDIOptions> options)
        {
            var optionsObj = new DataFwDIOptions();

            options(optionsObj);

            services.AddRepositoriesPattern(optionsObj);
        }
Example #2
0
        public static void AddRepositoriesPattern(this IServiceCollection services, DataFwDIOptions options)
        {
            // Collect types
            foreach (var assembly in options.Assemblies)
            {
                foreach (var type in assembly.DefinedTypes)
                {
                    // Repository
                    if (type.IsClass && options.RepositoryNamespaces.Contains(type.Namespace))
                    {
                        var interfaces = type.ImplementedInterfaces;

                        foreach (var i in interfaces)
                        {
                            services.AddScoped(i, type);
                        }
                    }

                    // Services
                    if (type.IsClass && options.ServiceNamespaces.Contains(type.Namespace))
                    {
                        var interfaces = type.ImplementedInterfaces;

                        foreach (var i in interfaces)
                        {
                            services.AddScoped(i, type);
                        }
                    }
                }
            }

            // Unit of Work
            if (options.UnitOfWorkType != null)
            {
                services.AddScoped(typeof(IUnitOfWork), options.UnitOfWorkType);
            }

            if (options.UnitOfWorkAsyncType != null)
            {
                services.AddScoped(typeof(IUnitOfWorkAsync), options.UnitOfWorkAsyncType);
            }

            // Inject DbContexts
            foreach (var dbContextType in options.DataContextTypes)
            {
                if (!typeof(DbContext).IsAssignableFrom(dbContextType))
                {
                    throw new ArgumentException("The type provided is not subclass of DbContext: " + dbContextType.FullName);
                }

                services.AddScoped(typeof(DbContext), dbContextType);
            }
        }