public static void Initialize() { var config = GlobalConfiguration.Configuration; var container = new Container(); container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior(); Configure(container); try { container.Verify(); } catch (Exception e) { Trace.TraceError("Failed to initialize IoC container: {0}", e); throw; } config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); container.RegisterWebApiFilterProvider(config); try { new TraceListenersInitializer(container.GetInstance<IPortalMiddleendSettings>(), container.GetInstance<IEmailSenderService>()).Initialize(); } catch (Exception e) { Trace.TraceError("Failed to initialize trace listeners: {0}", e); throw; } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterWebApiFilters(GlobalConfiguration.Configuration.Filters); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); FormatConfig.RegisterFormats(GlobalConfiguration.Configuration.Formatters); // Allow Any Certificates // This should not be the same in Production ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; // Simple Injection Setup var container = new Container(); container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior(); // SI Controllers registry container.Register<ICommentsResource, CommentsResource>(Lifestyle.Singleton); container.Register<ICommunityResource, CommunityResource>(Lifestyle.Singleton); container.Register<ICommentLikesResource, CommentLikesResource>(Lifestyle.Singleton); container.Register<IPostsResource, PostsResource>(Lifestyle.Singleton); container.Register<IUsersResource, UsersResource>(Lifestyle.Singleton); container.Register<IPostLikesResource, PostLikesResource>(Lifestyle.Singleton); container.Register<IPostContentsResource, PostContentsResource>(Lifestyle.Singleton); container.Register<IMediaResource, MediaResource>(Lifestyle.Singleton); container.Register<IAlbumResource, AlbumResource>(Lifestyle.Singleton); container.Register<IEducationResource, EducationResource>(Lifestyle.Singleton); container.Register<IHobbyResource, HobbyResource>(Lifestyle.Singleton); container.Register<IAddressResource, AddressResource>(Lifestyle.Singleton); container.Register<ITagsResource, TagsResource>(Lifestyle.Singleton); container.Register<IViewCountResource, ViewCountResource>(Lifestyle.Singleton); container.Register<IChatMessagesResource, ChatMessagesResource>(Lifestyle.Singleton); // SI Helpers and Utilities registry container.Register<IImageHelper, ImageHelper>(Lifestyle.Singleton); container.Register<IErrorSignaler, ErrorSignaler>(Lifestyle.Singleton); container.Register<IHttpClientHelper, HttpClientHelper>(Lifestyle.Singleton); container.Register<IConfigurationHelper, ConfigurationHelper>(Lifestyle.Singleton); // SI Token Identity registry container.Register<IdentityDbContext<BlogUser>, BlogIdentityDbContext>(Lifestyle.Singleton); container.Register<IUserStore<BlogUser>, BlogUserStore>(Lifestyle.Singleton); container.Register<IBlogDbRepository, BlogDbRepository>(Lifestyle.Singleton); container.Register<BlogUserManager, BlogUserManager>(Lifestyle.Singleton); // SI Registrations container.RegisterMvcControllers(System.Reflection.Assembly.GetExecutingAssembly()); container.RegisterMvcIntegratedFilterProvider(); container.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); container.Verify(); // Register the dependency resolver. GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); GlobalConfiguration.Configuration.EnsureInitialized(); }
public static Container CreateContainer() { var container = new Container(); container.Options.AllowOverridingRegistrations = true; container.Options.PropertySelectionBehavior = new InjectAttributePropertySelectionBehavior(); container.RegisterPackage<Bootstrapper>(); container.RegisterMvcControllers(Assembly.GetExecutingAssembly()); container.RegisterMvcAttributeFilterProvider(); container.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); return container; }
/// <summary> /// Initializes this instance. /// </summary> public static void Initialize(Container container) { try { //var container = SimpleDependencyInjector.Instance; container.RegisterPackages(); container.RegisterWebApiControllers(GlobalConfiguration.Configuration); container.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); container.RegisterMvcControllers(Assembly.GetExecutingAssembly()); container.RegisterMvcIntegratedFilterProvider(); container.Verify(); MapperInitializer.RegisterMapper(container); System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjector.Integration.Web.Mvc.SimpleInjectorDependencyResolver(container)); } catch (Exception ex) { ex.ExceptionValueTracker(); } }
public static void BuildWithContainer(IAppBuilder app, Container container, bool registerExceptionlessClient = true) { if (container == null) throw new ArgumentNullException("container"); // if enabled, auto upgrade the database if (Settings.Current.ShouldAutoUpgradeDatabase) { var url = new MongoUrl(Settings.Current.MongoConnectionString); string databaseName = url.DatabaseName; if (Settings.Current.AppendMachineNameToDatabase) databaseName += String.Concat("-", Environment.MachineName.ToLower()); MongoMigrationChecker.EnsureLatest(Settings.Current.MongoConnectionString, databaseName); } Config = new HttpConfiguration(); Config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); Config.Formatters.Remove(Config.Formatters.XmlFormatter); Config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented; Config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new LowerCaseUnderscorePropertyNamesContractResolver(); var constraintResolver = new DefaultInlineConstraintResolver(); constraintResolver.ConstraintMap.Add("objectid", typeof(ObjectIdRouteConstraint)); constraintResolver.ConstraintMap.Add("objectids", typeof(ObjectIdsRouteConstraint)); Config.MapHttpAttributeRoutes(constraintResolver); //config.EnableSystemDiagnosticsTracing(); container.RegisterSingle<JsonSerializer>(JsonSerializer.Create(new JsonSerializerSettings { ContractResolver = new SignalRContractResolver() })); container.RegisterWebApiFilterProvider(Config); try { container.Verify(); } catch (Exception ex) { var tempEx = ex; while (!(tempEx is ReflectionTypeLoadException)) { if (tempEx.InnerException == null) break; tempEx = tempEx.InnerException; } var typeLoadException = tempEx as ReflectionTypeLoadException; if (typeLoadException != null) { foreach (var loaderEx in typeLoadException.LoaderExceptions) Debug.WriteLine(loaderEx.Message); } Debug.WriteLine(ex.Message); throw; } Config.MessageHandlers.Add(container.GetInstance<XHttpMethodOverrideDelegatingHandler>()); Config.MessageHandlers.Add(container.GetInstance<EncodingDelegatingHandler>()); Config.MessageHandlers.Add(container.GetInstance<AuthTokenMessageHandler>()); // Throttle api calls to X every 15 minutes by IP address. Config.MessageHandlers.Add(container.GetInstance<ThrottlingHandler>()); // Reject event posts in orgs over their max event limits. Config.MessageHandlers.Add(container.GetInstance<OverageHandler>()); app.UseCors(CorsOptions.AllowAll); app.CreatePerContext<Lazy<User>>("User", ctx => new Lazy<User>(() => { if (ctx.Request.User == null || ctx.Request.User.Identity == null || !ctx.Request.User.Identity.IsAuthenticated) return null; string userId = ctx.Request.User.GetUserId(); if (String.IsNullOrEmpty(userId)) return null; var userRepository = container.GetInstance<IUserRepository>(); return userRepository.GetById(userId, true); })); app.CreatePerContext<Lazy<Project>>("DefaultProject", ctx => new Lazy<Project>(() => { if (ctx.Request.User == null || ctx.Request.User.Identity == null || !ctx.Request.User.Identity.IsAuthenticated) return null; string projectId = ctx.Request.User.GetDefaultProjectId(); var projectRepository = container.GetInstance<IProjectRepository>(); if (String.IsNullOrEmpty(projectId)) return projectRepository.GetByOrganizationIds(ctx.Request.User.GetOrganizationIds(), useCache: true).FirstOrDefault(); return projectRepository.GetById(projectId, true); })); if (registerExceptionlessClient) { ExceptionlessClient.Default.RegisterWebApi(Config); Config.Services.Add(typeof(IExceptionLogger), new ExceptionlessExceptionLogger()); } app.UseWebApi(Config); app.MapSignalR("/api/v2/push", new HubConfiguration { Resolver = new SimpleInjectorSignalRDependencyResolver(container) }); PhysicalFileSystem fileSystem = null; var root = AppDomain.CurrentDomain.BaseDirectory; if (Directory.Exists(Path.Combine(root, "./Content"))) fileSystem = new PhysicalFileSystem(Path.Combine(root, "./Content")); if (Directory.Exists(Path.Combine(root, "./bin/Content"))) fileSystem = new PhysicalFileSystem(Path.Combine(root, "./bin/Content")); if (fileSystem != null) app.UseFileServer(new FileServerOptions { FileSystem = fileSystem }); Mapper.Configuration.ConstructServicesUsing(container.GetInstance); // TODO: Figure out what data we want to create when the db is empty in production mode. if (Settings.Current.WebsiteMode == WebsiteMode.Dev) EnsureSampleData(container); var context = new OwinContext(app.Properties); var token = context.Get<CancellationToken>("host.OnAppDisposing"); if (Settings.Current.EnableJobsModule) { Run.InBackground(t => container.GetInstance<ProcessEventPostsJob>().Run(token), token); Run.InBackground(t => container.GetInstance<ProcessEventUserDescriptionsJob>().Run(token), token); Run.InBackground(t => container.GetInstance<ProcessMailMessageJob>().Run(token), token); Run.InBackground(t => container.GetInstance<DailyNotificationJob>().Run(token), token); Run.InBackground(t => container.GetInstance<EnforceRetentionLimitsJob>().Run(token), token); Run.InBackground(t => container.GetInstance<RemoveStaleAccountsJob>().Run(token), token); } }
public static void BuildWithContainer(IAppBuilder app, Container container) { if (container == null) throw new ArgumentNullException("container"); var contractResolver = container.GetInstance<IContractResolver>(); var exceptionlessContractResolver = contractResolver as ExceptionlessContractResolver; if (exceptionlessContractResolver != null) exceptionlessContractResolver.UseDefaultResolverFor(typeof(Connection).Assembly); Config = new HttpConfiguration(); Config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); Config.Formatters.Remove(Config.Formatters.XmlFormatter); Config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented; Config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = contractResolver; SetupRouteConstraints(Config); container.RegisterWebApiFilterProvider(Config); VerifyContainer(container); container.Bootstrap(Config); container.Bootstrap(app); Log.Info().Message("Starting api...").Write(); Config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger()); Config.Services.Replace(typeof(IExceptionHandler), container.GetInstance<ExceptionlessReferenceIdExceptionHandler>()); Config.MessageHandlers.Add(container.GetInstance<XHttpMethodOverrideDelegatingHandler>()); Config.MessageHandlers.Add(container.GetInstance<EncodingDelegatingHandler>()); Config.MessageHandlers.Add(container.GetInstance<AuthMessageHandler>()); // Throttle api calls to X every 15 minutes by IP address. Config.MessageHandlers.Add(container.GetInstance<ThrottlingHandler>()); // Reject event posts in orgs over their max event limits. Config.MessageHandlers.Add(container.GetInstance<OverageHandler>()); app.UseCors(new CorsOptions { PolicyProvider = new CorsPolicyProvider { PolicyResolver = ctx => Task.FromResult(new CorsPolicy { AllowAnyHeader = true, AllowAnyMethod = true, AllowAnyOrigin = true, SupportsCredentials = true, PreflightMaxAge = 60 * 5 }) } }); app.CreatePerContext<Lazy<User>>("User", ctx => new Lazy<User>(() => { if (ctx.Request.User == null || ctx.Request.User.Identity == null || !ctx.Request.User.Identity.IsAuthenticated) return null; string userId = ctx.Request.User.GetUserId(); if (String.IsNullOrEmpty(userId)) return null; var userRepository = container.GetInstance<IUserRepository>(); return userRepository.GetById(userId, true); })); app.CreatePerContext<Lazy<Project>>("DefaultProject", ctx => new Lazy<Project>(() => { if (ctx.Request.User == null || ctx.Request.User.Identity == null || !ctx.Request.User.Identity.IsAuthenticated) return null; // TODO: Use project id from url. E.G., /projects/{projectId:objectid}/events string projectId = ctx.Request.User.GetDefaultProjectId(); var projectRepository = container.GetInstance<IProjectRepository>(); if (String.IsNullOrEmpty(projectId)) { var firstOrgId = ctx.Request.User.GetOrganizationIds().FirstOrDefault(); if (!String.IsNullOrEmpty(firstOrgId)) { var project = projectRepository.GetByOrganizationId(firstOrgId, useCache: true).Documents.FirstOrDefault(); if (project != null) return project; } if (Settings.Current.WebsiteMode == WebsiteMode.Dev) { var dataHelper = container.GetInstance<DataHelper>(); // create a default org and project projectId = dataHelper.CreateDefaultOrganizationAndProject(ctx.Request.GetUser()); } } if (String.IsNullOrEmpty(projectId)) return null; return projectRepository.GetById(projectId, true); })); app.UseWebApi(Config); var resolver = new SimpleInjectorSignalRDependencyResolver(container); if (Settings.Current.EnableRedis) resolver.UseRedis(new RedisScaleoutConfiguration(Settings.Current.RedisConnectionString, "exceptionless.signalr")); app.MapSignalR("/api/v2/push", new HubConfiguration { Resolver = resolver }); SetupSwagger(Config); Mapper.Configuration.ConstructServicesUsing(container.GetInstance); CreateSampleData(container); if (Settings.Current.RunJobsInProcess) { Log.Warn().Message("Jobs running in process.").Write(); var context = new OwinContext(app.Properties); var token = context.Get<CancellationToken>("host.OnAppDisposing"); JobRunner.RunContinuousAsync<EventPostsJob>(cancellationToken: token); JobRunner.RunContinuousAsync<EventUserDescriptionsJob>(cancellationToken: token); JobRunner.RunContinuousAsync<MailMessageJob>(cancellationToken: token); JobRunner.RunContinuousAsync<EventNotificationsJob>(cancellationToken: token); JobRunner.RunContinuousAsync<WebHooksJob>(cancellationToken: token); JobRunner.RunContinuousAsync<DailySummaryJob>(cancellationToken: token, interval: TimeSpan.FromHours(1)); JobRunner.RunContinuousAsync<DownloadGeoIPDatabaseJob>(cancellationToken: token, interval: TimeSpan.FromDays(1)); JobRunner.RunContinuousAsync<RetentionLimitsJob>(cancellationToken: token, interval: TimeSpan.FromDays(1)); JobRunner.RunContinuousAsync<WorkItemJob>(instanceCount: 2, cancellationToken: token); } else { Log.Info().Message("Jobs running out of process.").Write(); } }