public static void AddNHibernateSessionFactory(this IServiceCollection services)
        {
            // By default NHibernate looks for hibernate.cfg.xml
            // otherwise for Web it will fallback to web.config
            // we got one under wwwroot/web.config
            Configuration config = new Configuration();
            config.Configure();

            // Auto load entity mapping class
            ModelMapper mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetAssembly(typeof(Employee)).GetExportedTypes());

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            config.AddDeserializedMapping(mapping, "NHibernate.Mapping");

            SchemaMetadataUpdater.QuoteTableAndColumns(config);

            // Drop & Recreate database schema
            new SchemaExport(config).Drop(false, true);
            new SchemaExport(config).Create(false, true);

            // Register services
            services.AddSingleton<ISessionFactory>(provider => config.BuildSessionFactory());
            services.AddTransient<ISession>(provider => services.BuildServiceProvider().GetService<ISessionFactory>().OpenSession());
        }
        public static IServiceCollection AddPersistenceServices(this IServiceCollection services) {
            var config = services.BuildServiceProvider().GetRequiredService<IConfigurationRoot>();
            string connectionString = config["Data:ConnectionString"];
            services.AddEntityFramework()
                .AddSqlite()
                .AddDbContext<Context>(options => options.UseSqlite(connectionString));

            var database = services.BuildServiceProvider().GetService<Context>().Database;
            //https://github.com/aspnet/EntityFramework/issues/3160
            //EnsureCreated is designed for testing or rapid prototyping where you are ok with dropping and re-creating the database each time.
            //If you are using migrations and want to have them automatically applied on app start, then you can use context.Database.Migrate() instead
            //database.EnsureCreated();     
            database.Migrate();

            return services;
        }
        public static void AddBrickPile(this IServiceCollection services)
        {
            _serviceProvider = services.BuildServiceProvider();

            services.AddMvc().ConfigureApplicationPartManager(manager =>
            {
                var feature = new ControllerFeature();
                manager.PopulateFeature(feature);
                services.AddSingleton<IControllerMapper>(new ControllerMapper(feature));
            });

            services.AddRouting(options =>
            {
                options.AppendTrailingSlash = true;
                options.LowercaseUrls = true;
            });

            services.Configure<MvcOptions>(options =>
            {
                options.ModelBinderProviders.Insert(0, new DefaultModelBinderProvider(DocumentStore));
                options.Filters.Add(typeof(PublishedFilterAttribute), 1);
                options.Filters.Add(typeof(AuthorizeFilterAttribute), 2);
            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton(DocumentStore);
            services.AddTransient<IRouteResolverTrie>(provider => new RouteResolverTrie(provider.GetService<IDocumentStore>()));
            services.AddTransient<IBricsContextAccessor>(provider => new BricsContextAccessor(provider.GetService<IHttpContextAccessor>(), provider.GetService<IDocumentStore>()));
        }
        public static IServiceCollection AddOrchardMvc(this IServiceCollection services)
        {
            services
                .AddMvcCore(options =>
                {
                    options.Filters.Add(new ModelBinderAccessorFilter());
                    options.Filters.Add(typeof(AutoValidateAntiforgeryTokenAuthorizationFilter));
                    options.ModelBinderProviders.Insert(0, new CheckMarkModelBinderProvider());
                })
                .AddViews()
                .AddViewLocalization()
                .AddRazorViewEngine()
                .AddJsonFormatters();

            services.AddScoped<IModelUpdaterAccessor, LocalModelBinderAccessor>();
            services.AddTransient<IFilterProvider, DependencyFilterProvider>();
            services.AddTransient<IApplicationModelProvider, ModuleAreaRouteConstraintApplicationModelProvider>();

            services.Configure<RazorViewEngineOptions>(configureOptions: options =>
            {
                var expander = new ModuleViewLocationExpander();
                options.ViewLocationExpanders.Add(expander);

                var extensionLibraryService = services.BuildServiceProvider().GetService<IExtensionLibraryService>();
                ((List<MetadataReference>)options.AdditionalCompilationReferences).AddRange(extensionLibraryService.MetadataReferences());
            });

            return services;
        }
 private static RegisterDependencyType GetDependencyScanner(this IServiceCollection services)
 {
     var scanner = services.BuildServiceProvider().GetService<RegisterDependencyType>();
     if (null == scanner)
     {
         throw new InvalidOperationException(
             "Unable to resolve scanner. Call services.AddDependencyScanner");
     }
     return scanner;
 }
        public static IServiceCollection AddConfiguration(this IServiceCollection self, string fileName = "config")
        {
            var services = self.BuildServiceProvider();
            var env = services.GetRequiredService<IHostingEnvironment>();

            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile($"{fileName}.json")
                .AddJsonFile($"{fileName}.{env.EnvironmentName}.json", optional: true);
            var configuration = builder.Build();
            self.AddSingleton<IConfiguration>(configuration);

            return self;
        }
        public static GlimpseServiceCollectionBuilder AddGlimpse(this IServiceCollection services, bool autoRegisterComponents)
        {
            // load in default services
            services.TryAdd(CommonServices.GetDefaultServices());
            
            // run all other service registrations (i.e. agent and server)
            if (autoRegisterComponents)
            {
                var extensionProvider = services.BuildServiceProvider().GetService<IExtensionProvider<IRegisterServices>>();
                foreach (var registration in extensionProvider.Instances)
                {
                    registration.RegisterServices(services);
                }
            }

            return new GlimpseServiceCollectionBuilder(services);
        } 
        public static IServiceCollection AddSmashLeagueAuthorization(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddTransient<TeamOwnerRequirement>();

            var provider = services.BuildServiceProvider();

            services.AddAuthorization(x =>
            {
                x.AddTeamOwnerPolicy(provider);
            });

            return services;
        }
        public static IServiceCollection AddMediator(this IServiceCollection services)
        {
            services.AddScoped<IMediator>(
                servicesProvider => new Mediator(servicesProvider.GetService, servicesProvider.GetServices));

            var libraryManager = services.BuildServiceProvider().GetService<ILibraryManager>();

            var assemblies = libraryManager
                .GetReferencingLibraries("MediatR")
                .Distinct()
                .SelectMany(l => l.Assemblies)
                .Select(Assembly.Load);

            var asyncHandlerTypes = assemblies
                .SelectMany(a => a.DefinedTypes)
                .Where(typeInfo => !typeInfo.IsAbstract && typeInfo.GetInterfaces().Any(x =>
                    x.IsGenericType && x.GetGenericTypeDefinition() == typeof (IAsyncRequestHandler<,>)));

            foreach (var type in asyncHandlerTypes)
            {
                var interfaceType =
                    type.GetInterfaces().First(x => x.GetGenericTypeDefinition() == typeof (IAsyncRequestHandler<,>));
                services.AddScoped(interfaceType, type);
            }

            var handlerTypes = assemblies
                .SelectMany(a => a.DefinedTypes)
                .Where(typeInfo => !typeInfo.IsAbstract && typeInfo.GetInterfaces().Any(x =>
                    x.IsGenericType && x.GetGenericTypeDefinition() == typeof (IRequestHandler<,>)));

            foreach (var type in handlerTypes)
            {
                var interfaceType =
                    type.GetInterfaces().First(x => x.GetGenericTypeDefinition() == typeof (IRequestHandler<,>));
                services.AddScoped(interfaceType, type);
            }

            return services;
        }
 public static IServiceCollection AddInovicesBusinessServices(this IServiceCollection services, bool seedData) {
     services.AddPersistenceServices();
     services.AddTransient<ICustomersService, CustomersService>();
     SampleData.SeedData(services.BuildServiceProvider()).Wait();
     return services;
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Creates new <see cref="IServiceProvider"/> based on service collection.
 /// </summary>
 /// <param name="serviceCollection">Service collection to create provider from.</param>
 /// <returns></returns>
 public static IServiceProvider CreateServiceProvider(this IServiceCollection serviceCollection)
 {
     // Save the list of service definitions
     serviceCollection.AddSingleton(_ => serviceCollection);
     return serviceCollection.BuildServiceProvider();
 }
 public static IServiceProvider BuilderAppServiceProvider(this IServiceCollection services)
 {
     AssemblyApi.AssemblyManager.ConfigureModuleServices(services);
     return services.BuildServiceProvider();
 }
        /// <summary>
        /// Configures custom services to add to the ASP.NET MVC 6 Injection of Control (IoC) container.
        /// </summary>
        /// <param name="services">The services collection or IoC container.</param>
        public static void ConfigureCoreServices(this IServiceCollection services)
        {
            #region Antiforgery
            services.ConfigureAntiforgery(
                    antiforgeryOptions =>
                    {
                        // Rename the Anti-Forgery cookie from "__RequestVerificationToken" to "f". This adds a little 
                        // security through obscurity and also saves sending a few characters over the wire. 
                        antiforgeryOptions.CookieName = "f";

                        // Rename the form input name from "__RequestVerificationToken" to "f" for the same reason above 
                        // e.g. <input name="__RequestVerificationToken" type="hidden" value="..." />
                        antiforgeryOptions.FormFieldName = "f";

                        // If you have enabled SSL/TLS. Uncomment this line to ensure that the Anti-Forgery cookie requires 
                        // SSL /TLS to be sent across the wire. 
                        // $Start-HttpsEverywhere$
                        // antiforgeryOptions.RequireSsl = true;
                        // $End-HttpsEverywhere$
                    });
            services.AddAntiforgery();
            #endregion

            #region Configuration

            var applicationEnvironment = services.BuildServiceProvider().GetRequiredService<IApplicationEnvironment>();
            var hostingEnvironment = services.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
            //var configurationPath = Path.Combine(applicationEnvironment.ApplicationBasePath, "config.json");

            // Set up configuration sources.
            var configBuilder = new ConfigurationBuilder()
                .SetBasePath(applicationEnvironment.ApplicationBasePath)
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: true)
                //All environment variables in the process's context flow in as configuration values.
                .AddEnvironmentVariables();

            Configuration = configBuilder.Build();

            services.AddSingleton(_ => Configuration as IConfiguration);

           
            #endregion  

            #region Logging


            services.AddLogging();
            

            #endregion

           

            #region Caching
            // Adds a default in-memory implementation of IDistributedCache, which is very fast but 
            // the cache will not be shared between instances of the application. 
            // Also adds IMemoryCache.
            services.AddCaching();

            // Uncomment the following line to use the Redis implementation of      
            // IDistributedCache. This will override any previously registered IDistributedCache 
            // service. Redis is a very fast cache provider and the recommended distributed cache 
            // provider.
            // services.AddTransient<IDistributedCache, RedisCache>();

            // Uncomment the following line to use the Microsoft SQL Server implementation of 
            // IDistributedCache. Note that this would require setting up the session state database.
            // Redis is the preferred cache implementation but you can use SQL Server if you don't 
            // have an alternative.
            // services.AddSqlServerCache(o =>
            // {
            //     o.ConnectionString = 
            //       "Server=.;Database=ASPNET5SessionState;Trusted_Connection=True;";
            //     o.SchemaName = "dbo";
            //     o.TableName = "Sessions";
            // });
            #endregion

            #region Session
            services.AddSession(o =>
            {
                //o.IdleTimeout = TimeSpan.FromMinutes(Double.Parse(Configuration[TimeoutConfigKey]));
                o.IdleTimeout = TimeSpan.FromMinutes(15);
            });
            #endregion

            #region Localization
            services.AddLocalization();
            #endregion

        }