Exemple #1
0
        public void Configuration(IAppBuilder appBuilder)
        {
            // Set up server configuration
            HttpConfiguration config = new HttpConfiguration();

            // DscQRouteHandler
            config.MessageHandlers.Add(new DscQRouteHandler());

            config.MapODataServiceRoute(
                routeName: "DscQuery",
                routePrefix: "{datasource}/{path}/odata",
                model: GetQueryEdmModel());

            #region DI
            Container = new Container(rules => rules.WithoutThrowOnRegisteringDisposableTransient()).WithWebApi(config);

            Container.RegisterMany(new [] { GetType().Assembly }, (registrator, types, type) =>
            {
                Type[] interfaces = type.GetInterfaces();

                bool assignedFromDispatcher = interfaces.Any(i => i.IsAssignableTo(typeof(IJobDispatcher)) || i.IsAssignableTo(typeof(IQueryDispatcher)));

                if (assignedFromDispatcher || interfaces.Any(i => i.IsAssignableTo(typeof(IInterceptor)) ||
                                                             i.IsAssignableTo(typeof(IJob)) ||
                                                             i.IsAssignableTo(typeof(IQuery)) ||
                                                             (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IQueryHandler <,>))))
                {
                    // all dispatchers --> Reuse.InCurrentScope
                    IReuse reuse = assignedFromDispatcher
                        ? Reuse.InResolutionScope
                        : Reuse.Transient;

                    registrator.RegisterMany(types, type, reuse);

                    // interceptors
                    if (type.IsClass)
                    {
                        InterceptedObjectAttribute attr = (InterceptedObjectAttribute)type.GetCustomAttribute(typeof(InterceptedObjectAttribute));
                        if (attr != null)
                        {
                            Type serviceType = attr.ServiceInterfaceType ?? type.GetImplementedInterfaces().FirstOrDefault();
                            registrator.Intercept(serviceType, attr.InterceptorType);
                        }
                    }
                }
            });

            Container.RegisterInstance((IOracleEnvironmentConfiguration)System.Configuration.ConfigurationManager.GetSection("oracleEnvironment"));
            Container.RegisterInstance(System.Configuration.ConfigurationManager.AppSettings["ProviderName"], serviceKey: "ProviderName");
            Container.Register(
                reuse: Reuse.InResolutionScope,
                made: Made.Of(() => DbManagerFactory.CreateDbManager(Arg.Of <string>("ProviderName"), null), requestIgnored => string.Empty)
                );

            // IDbManager initialiazation
            Container.RegisterInitializer <IDbManager>((m, r) => m.Log = Log.Logger.Debug);

            // cache manager
            Container.Register(reuse: Reuse.Singleton, made: Made.Of(() => CacheFactory.FromConfiguration <object>("webCache")));

            Container.UseInstance(Container);
            #endregion

            // Startup Jobs
            IJobDispatcher dispatcher = Container.Resolve <IJobDispatcher>(IfUnresolved.ReturnDefault);
            dispatcher?.Dispatch <IStartupJob>();

            config.Filters.Add(new GlobalExceptionFilter());

            var odataFormatters = ODataMediaTypeFormatters.Create(new SkipNullValueODataSerializerProvider(), new DefaultODataDeserializerProvider());
            config.Formatters.InsertRange(0, odataFormatters);

            appBuilder.UseWebApi(config);
        }
Exemple #2
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddOptions();

            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            services.Configure <ConnectionOptions>(Configuration.GetSection("Data:DefaultConnection"));
            services.Configure <ForceHttpsOptions>(Configuration.GetSection("HttpsOptions"));
            services.Configure <OracleEnvironmentConfiguration>(Configuration.GetSection("OracleEnvironment"));
            services.Configure <List <Client> >(Configuration.GetSection("Clients"));

            //identityServer
            IIdentityServerBuilder builder = services
                                             .AddIdentityServer(options =>
            {
                options.UserInteractionOptions.LoginUrl   = "/login";
                options.UserInteractionOptions.LogoutUrl  = "/logout";
                options.UserInteractionOptions.ConsentUrl = "/consent";
                options.UserInteractionOptions.ErrorUrl   = "/error";
            });

            #region certificate
            string fileName = Path.Combine(_contentRootPath, "idsrv4test.pfx");
            if (File.Exists(fileName))
            {
                X509Certificate2 cert = new X509Certificate2(fileName, "idsrv3test");
                builder.AddSigningCredential(cert);
            }
            else
            {
                builder.AddTemporarySigningCredential();
            }

            #endregion

            #region clients (from clients.json)
            builder.Services.AddSingleton <IEnumerable <Client> >(provider => provider.GetService <IOptions <List <Client> > >().Value);
            builder.Services.AddTransient <IClientStore, InMemoryClientStore>();
            builder.Services.AddTransient <ICorsPolicyService, InMemoryCorsPolicyService>();
            #endregion

            #region resources
            builder.AddInMemoryIdentityResources(accounts.Configuration.Resources.GetIdentityResources());
            #endregion

            #region users --> empty list
            builder.AddProfileService <Services.ProfileService>();
            builder.Services.AddSingleton(new List <InMemoryUser>());
            builder.Services.AddTransient <IResourceOwnerPasswordValidator, InMemoryUserResourceOwnerPasswordValidator>();
            #endregion

            // for the UI
            services
            .AddMvc(options =>
            {
                options.ModelBinderProviders.Insert(0, new EncryptModelBinderProvider());
                options.CacheProfiles.Add("1hour", new CacheProfile()
                {
                    Duration = 3600
                });
            })
            .AddJsonOptions(option =>
            {
                option.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                option.SerializerSettings.ContractResolver  = new CamelCasePropertyNamesContractResolver();
            });

            services.AddRouting(options => options.LowercaseUrls = true);
            services.Configure <MvcOptions>(options => options.Filters.Add(new GlobalExceptionFilter()));            // Global exceptions' filter
            services.Configure <RazorViewEngineOptions>(options => options.FileProviders.Add(new EmbeddedFileProvider(GetType().Assembly, "accounts")));

            // Add dependencies
            IContainer container = ConfigureDependencies(services, "domain", "Kit.Core", "Kit.Dal", "Kit.Dal.Oracle");

            // IDbManager
            container.RegisterDelegate(delegate(IResolver r)
            {
                HttpContext httpContext = r.Resolve <IHttpContextAccessor>().HttpContext;

                ClaimsPrincipal cp = httpContext.User;
                string userId      = cp.Identity.Name;

                return(httpContext.User.ToString($"Data Source={{{ConnectionClaimTypes.DataSource}}};User Id={userId};Password={{{ConnectionClaimTypes.Password}}};"));
            }, serviceKey: "ConnectionString");

            container.RegisterDelegate(r => r.Resolve <IOptions <ConnectionOptions> >().Value.ProviderName, serviceKey: "ProviderName");

            container.Register(
                reuse: Reuse.InWebRequest,
                made: Made.Of(() => DbManagerFactory.CreateDbManager(Arg.Of <string>("ProviderName"), Arg.Of <string>("ConnectionString")), requestIgnored => string.Empty)
                );

            // Startup Jobs
            IJobDispatcher dispatcher = container.Resolve <IJobDispatcher>(IfUnresolved.ReturnDefault);
            dispatcher?.Dispatch <IStartupJob>();

            return(container.Resolve <IServiceProvider>());
        }