public ActionResult Index() { Container container = new Container(); string apiKey = System.Configuration.ConfigurationManager.AppSettings["LeagueApiKey"]; container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Singleton); container.Register<IJsonRequestService, JsonRequestService>(); container.Register<ILeagueApiService>(() => new LeagueApiService(container.GetInstance<IJsonRequestService>(), apiKey)); container.Register<IChampionRepository, ChampionRepository>(); container.Register<IItemRepository, ItemRepository>(); container.Register<IDtoMapper<Champion, ChampionDTO>, ChampionDTOMapper>(); container.Register<IDtoMapper<Item, ItemDTO>, ItemDTOMapper>(); container.Register<UpdateDatabaseFromApiService>(); container.Register<LeagueItemsContext>(Lifestyle.Singleton); container.Register<BuildGenerationService>(); container.Register<IBuildGenerationStrategy, HeuristicBuildGenerationStrategy>(); container.Verify(); BuildGenerationService buildGenerationService = container.GetInstance<BuildGenerationService>(); IUnitOfWork unitOfWork = container.GetInstance<IUnitOfWork>(); Champion jinx = unitOfWork.ChampionRepository.Get(106); List<Item> buildItems = buildGenerationService.GetItemsForBuild(jinx.Builds.First()); return View(buildItems); }
static void Main(string[] args) { //create the IOC container var container = new Container(); //bind all our types to the interfaces container.Register<IContactCreator, ContactCreator>(); container.Register<IContactLister, ContactLister>(); container.Register<IContactStore, MemoryContactStore>(); container.Register<ILog, NoLogging>(); var creator = container.GetInstance<IContactCreator>(); creator.Create(new Contact() { Name = "Guy" }); creator.Create(new Contact() { Name = "Ascension" }); creator.Create(new Contact() { Name = "Richard" }); var lister = container.GetInstance<IContactLister>(); var contacts = lister.GetList(); foreach (var contact in contacts) { Console.WriteLine(contact.Name); } Console.ReadKey(); }
// todo: only starting up subscriptions from web client for simplicity, should be done in console app (separate process) public void RegisterServices(Container container) { container.RegisterSingleton<ResolvedEventPublisher>(); container.Register<SubscriptionClient[]>(() => { // todo: json configuration for subscription clients string streamName = "$ce-user"; string groupName = "user-publisher"; PersistentSubscriptionSettingsBuilder settings = PersistentSubscriptionSettings.Create() .ResolveLinkTos() .StartFrom(0) .MinimumCheckPointCountOf(1) .MaximumCheckPointCountOf(1) ; try { IEventStoreConnection connection = container.GetInstance<Connection.IProvideConnection>().GetConnectionAsync().Result; // todo: should not be creating the persistent subscription from code http://docs.geteventstore.com/dotnet-api/3.3.1/competing-consumers/ connection.CreatePersistentSubscriptionAsync(streamName, groupName, settings, new UserCredentials("admin", "changeit")).Wait(); } catch (AggregateException ex) when (ex.InnerException.Message.Equals($"Subscription group {groupName} on stream {streamName} already exists")) { // subscription already exists } var userClients = new List<SubscriptionClient>(); Parallel.ForEach(Enumerable.Range(0, 9), x => { userClients.Add(new SubscriptionClient(streamName, groupName, container.GetInstance<Connection.IProvideConnection>(), container.GetInstance<ResolvedEventPublisher>())); }); return userClients.ToArray(); }, Lifestyle.Singleton); }
public void RegisterServices(Container container) { container.RegisterSingleton<IConfiguration, EnvironmentAwareAppSettingsConfiguration>(); container.RegisterSingleton(() => { var config = container.GetInstance<IConfiguration>(); var useRedis = config.Get("UseRedis"); IDataServiceFactory factory; if (bool.Parse(useRedis)) { factory = new RedisDataServiceFactory(config); } else { factory = new DirectDataServiceFactory(); } return factory; }); container.RegisterSingleton(() => container.GetInstance<IDataServiceFactory>().Create()); container.RegisterSingleton<IAppSettings, AppSettings>(); }
static void Main(string[] args) { var container = new Container(); RegisterInfrastructure(container); var assemblies = GetAssemblies().ToArray(); container.RegisterSingleton<IMediator, Mediator>(); container.RegisterSingleton(new SingleInstanceFactory(container.GetInstance)); container.RegisterSingleton(new MultiInstanceFactory(container.GetAllInstances)); container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies); container.Verify(); var mediator = container.GetInstance<IMediator>(); var commandsDbContext = container.GetInstance<ICommandsDbContext>(); Console.Write("creating users..."); Task.WaitAll(CreateUsersAsync(commandsDbContext, mediator)); Console.WriteLine("done!"); Console.Write("creating areas..."); Task.WaitAll(CreateAreasAsync(commandsDbContext, mediator)); Console.WriteLine("done!"); Console.Write("creating ideas..."); Task.WaitAll(CreateIdeasAsync(commandsDbContext, mediator)); Console.WriteLine("done!"); Console.Write("creating idea comments..."); Task.WaitAll(CreateIdeaCommentsAsync(commandsDbContext, mediator)); Console.WriteLine("done!"); Console.WriteLine("Feeding complete!"); Console.ReadLine(); }
public void SomeChooserBroken() { var choices = new List<char>() { 'c', 'b', 'e', 'a', 'd' }; var container = new Container(); var runner = container.GetInstance<RunnerBuilder>(); var fitness = container.GetInstance<FitnessScorer>(); var shadowRunners = runner.Create(choices).ToArray(); var descs = new List<string>(); for (int i = 0; i < shadowRunners.Length; i++) { var r = shadowRunners[i]; r.Score = fitness.CalculateScore(r); descs.Add(r.ToString()); } var count = descs.Count; }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Allow Any Certificates // This should not be the same in Production ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; // Create the container as usual. var container = new Container(); container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior(); container.Register<IErrorSignaler, ErrorSignaler>(Lifestyle.Singleton); container.Register<IHttpClientHelper, HttpClientHelper>(Lifestyle.Singleton); container.Register<IConfigurationHelper, ConfigurationHelper>(Lifestyle.Singleton); // SI Attributes Dependency Injection container.RegisterInitializer<BlogApiAuthorizationAttribute>(a => a.ErrorSignaler = container.GetInstance<ErrorSignaler>()); container.RegisterInitializer<BlogAuthorizationAttribute>(a => a.ErrorSignaler = container.GetInstance<ErrorSignaler>()); // This is an extension method from the integration package. container.RegisterMvcControllers(System.Reflection.Assembly.GetExecutingAssembly()); container.RegisterMvcIntegratedFilterProvider(); container.Verify(); DependencyResolver.SetResolver(new SimpleInjector.Integration.Web.Mvc.SimpleInjectorDependencyResolver(container)); }
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; } }
private static void RunApp(Container container) { try { XamlGeneratedNamespace.GeneratedApplication app = new XamlGeneratedNamespace.GeneratedApplication(); ((WpfApplication)container.GetInstance<IApplication>()).Initialize(); app.InitializeComponent(); app.Startup += (sender, args) => { ThemeManager.AddAccent("WhiteAccent", new Uri("pack://application:,,,/DSImager.Application;component/Themes/WhiteAccent.xaml")); ThemeManager.AddAppTheme("WhiteTheme", new Uri("pack://application:,,,/DSImager.Application;component/Themes/WhiteTheme.xaml")); }; var mainWin = container.GetInstance<MainWindow>(); container.GetInstance<ILogService>().Trace(LogEventCategory.Informational, "App is starting"); app.Run(mainWin); } catch (Exception e) { Console.WriteLine(e.ToString()); throw; } }
private static void ConfigureAspNetIdentity(Container container) { container.Register( typeof(IUserStore<Administrator>), () => { var session = container.GetInstance<IAsyncDocumentSession>(); session.Advanced.UseOptimisticConcurrency = true; return new RavenUserStore<Administrator, RavenRole>(session); }, Lifestyle.Scoped); container.Register( typeof(UserManager<Administrator>), () => { var manager = new UserManager<Administrator>(container.GetInstance<IUserStore<Administrator>>()); manager.UserValidator = new UserValidator<Administrator>(manager) { AllowOnlyAlphanumericUserNames = false, }; return manager; }, Lifestyle.Scoped); }
/// <summary>Initialize the container and register it as MVC3 Dependency Resolver.</summary> public static void Initialize() { var container = new Container(); InitializeContainer(container); try { container.Verify(); } catch (Exception exception) { Trace.TraceError("{0}", exception); throw; } GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); GlobalConfiguration.Configuration.Services.Replace(typeof (IFilterProvider), new SimpleInjectorWebApiFilterProvider(container)); try { new TraceListenersInitializer(container.GetInstance<IPortalSettings>(), container.GetInstance<IEmailSenderService>()).Initialize(); } catch (Exception e) { Trace.TraceError("Failed to initialize trace listeners: {0}", e); throw; } }
public override bool OnStart() { var container = new Container(); try { // Building IoC container Initialize(container); container.Verify(); // Initializers var initializers = new List<IInitializable> { container.GetInstance<TraceListenersInitializer>(), container.GetInstance<DiagnosticsInitializer>() }; foreach (IInitializable initializer in initializers) { initializer.Initialize(); } } catch (Exception e) { Trace.TraceError("Failed to start BillingSync worker role: {0}", e); throw; } _container = container; return base.OnStart(); }
public void RegisterServices(Container container) { container.RegisterSingle<IDependencyResolver>(() => new SimpleInjectorCoreDependencyResolver(container)); if (Settings.Current.EnableAppStats) container.RegisterSingle<IAppStatsClient>(() => new AppStatsClient(Settings.Current.AppStatsServerName, Settings.Current.AppStatsServerPort)); else container.RegisterSingle<IAppStatsClient, NullAppStatsClient>(); if (Settings.Current.RedisConnectionInfo == null) throw new ConfigurationErrorsException("RedisConnectionString was not found in the Web.config."); container.RegisterSingle<IDependencyResolver>(() => new SimpleInjectorCoreDependencyResolver(container)); container.RegisterSingle<IRedisClientsManager>(() => new PooledRedisClientManager(Settings.Current.RedisConnectionInfo.ToString())); container.Register<ICacheClient>(() => container.GetInstance<IRedisClientsManager>().GetCacheClient()); container.RegisterSingle<MongoDatabase>(() => { if (String.IsNullOrEmpty(Settings.Current.MongoConnectionString)) throw new ConfigurationErrorsException("MongoConnectionString was not found in the Web.config."); MongoDefaults.MaxConnectionIdleTime = TimeSpan.FromMinutes(1); var url = new MongoUrl(Settings.Current.MongoConnectionString); string databaseName = url.DatabaseName; if (Settings.Current.AppendMachineNameToDatabase) databaseName += String.Concat("-", Environment.MachineName.ToLower()); MongoServer server = new MongoClient(url).GetServer(); return server.GetDatabase(databaseName); }); container.Register<ErrorStatsHelper>(); container.RegisterSingle<IErrorStackRepository, ErrorStackRepository>(); container.RegisterSingle<IErrorRepository, ErrorRepository>(); container.RegisterSingle<IOrganizationRepository, OrganizationRepository>(); container.RegisterSingle<IJobLockInfoRepository, JobLockRepository>(); container.RegisterSingle<IJobHistoryRepository, JobHistoryRepository>(); container.RegisterSingle<IProjectRepository, ProjectRepository>(); container.RegisterSingle<IUserRepository, UserRepository>(); container.RegisterSingle<IProjectHookRepository, ProjectHookRepository>(); container.RegisterSingle<MongoCollection<User>>(() => container.GetInstance<UserRepository>().Collection); container.RegisterSingle<IEmailGenerator>(() => new RazorEmailGenerator(@"Mail\Templates")); container.RegisterSingle<IMailer, Mailer>(); container.RegisterSingle<IMessageService, ExceptionlessMqServer>(); container.Register<IMessageFactory>(() => container.GetInstance<IMessageService>().MessageFactory); container.Register<IDependencyResolver, SimpleInjectorCoreDependencyResolver>(); container.Register<MongoJobHistoryProvider>(); container.Register<MongoJobLockProvider>(); container.Register<MongoMachineJobLockProvider>(); container.Register<StartMqJob>(); container.Register<ErrorSignatureFactory>(); container.Register<StripeEventHandler>(); container.RegisterSingle<BillingManager>(); container.RegisterSingle<DataHelper>(); }
public HumanStrategy(Container container) { var randomCodeGenerator = container.GetInstance<IRandomCodeGenerator>(); _verifier = container.GetInstance<IVerifier>(); _guessHistory = new Queue<VerificationResult>(); _randomCode = randomCodeGenerator.Generate(); }
public void PerformTest() { var spCont = new SimpleInjector.Container(); spCont.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); spCont.Register <ICentralConfigProvider, TestConfigProvider>(Lifestyle.Scoped); using (AsyncScopedLifestyle.BeginScope(spCont)) { spCont.GetInstance <ICentralConfigProvider>(); } var autofacBd = new Autofac.ContainerBuilder(); autofacBd.RegisterType <TestConfigProvider>().As <ICentralConfigProvider>(); var autofac = autofacBd.Build(); using (var scope = autofac.BeginLifetimeScope()) { autofac.Resolve <ICentralConfigProvider>(); } var count = 1000; Console.WriteLine($"Start test {count} times: -----------------------"); //----SimpleInjector var task = Task.Run(() => TestUtil.RunWatch("SimpleInjector", count, () => { using (AsyncScopedLifestyle.BeginScope(spCont)) { var siIns = spCont.GetInstance <ICentralConfigProvider>(); } })); //------------------------------------------------- var task1 = Task.Run(() => TestUtil.RunWatch("Autofac", count, () => { using (var scope = autofac.BeginLifetimeScope()) { autofac.Resolve <ICentralConfigProvider>(); } })); //----SimpleInjector /*var task = Task.Run(() => TestUtil.RunWatch("Castle", count, () => * { * using (castle.BeginScope()) * { * castle.Resolve<ICentralConfigProvider>(); * } * }));*/ task.Wait(); task1.Wait(); }
public object Resolve(Type resolve) { if (!HasComponent(resolve)) { throw new ActivationException($"The requested type {resolve.FullName} is not registered yet"); } return(_container.GetInstance(resolve)); }
private static IEnumerable<IWebDriver> AllBrowsers(Container container) { if (container.GetRegistration(typeof(ChromeDriver)) != null) yield return container.GetInstance<ChromeDriver>(); if (container.GetRegistration(typeof(InternetExplorerDriver)) != null) yield return container.GetInstance<InternetExplorerDriver>(); if (container.GetRegistration(typeof(FirefoxDriver)) != null) yield return container.GetInstance<FirefoxDriver>(); }
public void RegisterInitializer_BaseClass_RunsInitializerOnSubClass() { var container = new Container(); container.Register<ITestService, TestService>(); container.RegisterInitializer<TestContainer>(c => c.TestService = container.GetInstance<ITestService>()); var testContainer = container.GetInstance<TestContainerDerivative>(); testContainer.ShouldNotBeNull(); testContainer.TestService.ShouldNotBeNull(); }
public static void Initialize() { // Create the container as usual. var container = new Container(); //setup logger container.RegisterSingle<ILogger>(() => new LoggerConfiguration() .WriteTo.ColoredConsole() .WriteTo.Trace() .CreateLogger() ); //instagram config for InstaSharp container.RegisterSingle<InstagramConfig>(() => { var clientId = ConfigurationManager.AppSettings["clientId"]; var clientSecret = ConfigurationManager.AppSettings["clientSecret"]; var callbackUri = ConfigurationManager.AppSettings["callbackUri"]; var redirectUri = ConfigurationManager.AppSettings["redirectUri"]; var icfg = new InstagramConfig(clientId, clientSecret); icfg.CallbackUri = callbackUri; icfg.RedirectUri = redirectUri; return icfg; } ); // Azure storage account container.RegisterSingle(() => { var connectionString = ConfigurationManager.AppSettings["StorageConnectionString"]; return CloudStorageAccount.Parse(connectionString); }); // Azure table client container.RegisterSingle(() => container.GetInstance<CloudStorageAccount>().CreateCloudTableClient()); //register our tablesets, in this case we only have one container.RegisterWebApiRequest<ITableSet<RealtimeSubscription>>(() => new TableSet<RealtimeSubscription>(container.GetInstance<CloudTableClient>()) ); //register repositories container.Register<ISubscriptionRepository, SubscriptionRepository>(Lifestyle.Singleton); // This is an extension method from the integration package. container.RegisterWebApiControllers(GlobalConfiguration.Configuration); container.Verify(); GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); }
static void Main(string[] args) { #region SimpleInjector var container = new Container(); container.Register<IMessageParser, MessageParser>(); container.Register<IMessageStorage>(()=> new MemoryStorage(10000)); container.Verify(); #endregion UDPListener listener = new UDPListener(8888); listener.StartListener(container.GetInstance<IMessageStorage>(), container.GetInstance<IMessageParser>()); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BootstrapBundleConfig.RegisterBundles(); var container = new Container(); container.Options.DefaultScopedLifestyle = new WebRequestLifestyle(); container.RegisterSingleton<ILinqToLdapLogger>(new SimpleTextLogger()); container.RegisterSingleton<ILdapConfiguration>(() => { var config = new LdapConfiguration() .MaxPageSizeIs(50) .LogTo(container.GetInstance<ILinqToLdapLogger>()); //Note the optional parameters available on AddMapping. //We can perform "late" mapping on certain values, //even for auto and attribute based mapping. config.AddMapping(new OrganizationalUnitMap()) .AddMapping(new AttributeClassMap<User>()); // I explicitly mapped User, but I can also let it // get mapped the first time we query for users. // This only applies to auto and attribute-based mapping. config.ConfigurePooledFactory("directory.utexas.edu") .AuthenticateBy(AuthType.Anonymous) .MinPoolSizeIs(0) .MaxPoolSizeIs(5) .UsePort(389) .ProtocolVersion(3); return config; }); //simple context per request only when requested container.Register<IDirectoryContext>(() => container.GetInstance<ILdapConfiguration>().CreateContext(), Lifestyle.Scoped); container.RegisterWebApiControllers(GlobalConfiguration.Configuration); container.RegisterMvcControllers(Assembly.GetExecutingAssembly()); GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container)); container.Verify(); }
public static void Configure() { Container = new Container(); Container.Register(() => HttpContext.Current.GetOwinContext()); Container.RegisterPerWebRequest(()=> Container.GetInstance<IOwinContext>().Authentication); Container.RegisterPerWebRequest(() => AppUserManager.Create(new IdentityFactoryOptions<AppUserManager>(), Container.GetInstance<IOwinContext>())); Container.RegisterPerWebRequest(AppDbContext.Create); Container.RegisterPerWebRequest<DbContext>(() => Container.GetInstance<AppDbContext>()); RepositoryRegistry.InsertIn(Container); }
static void Main(string[] args) { Console.WriteLine("HELLO WORLD"); try { using (var container = new SimpleInjector.Container()) { // Magnesium container.Register <Magnesium.MgDriverContext>(Lifestyle.Singleton); // Magnesium.VUlkan container.Register <Magnesium.IMgEntrypoint, Magnesium.Vulkan.VkEntrypoint>(Lifestyle.Singleton); container.Register <Magnesium.IMgImageTools, Magnesium.MgImageTools>(Lifestyle.Singleton); container.Register <IKTXTextureLoader, KTXTextureManager>(Lifestyle.Singleton); container.Register <IMgTextureGenerator, MgStagingBufferOptimizer>(Lifestyle.Singleton); container.Register <IMgGraphicsConfiguration, MgDefaultGraphicsConfiguration>(Lifestyle.Singleton); container.Register <IMgPresentationSurface, MgNullSurface>(Lifestyle.Singleton); using (var driver = container.GetInstance <Magnesium.MgDriverContext>()) { driver.Initialize( new MgApplicationInfo { ApplicationName = "Vulkan Example", ApiVersion = MgApplicationInfo.GenerateApiVersion(1, 0, 17), ApplicationVersion = 1, EngineName = "Magnesium", EngineVersion = 1, }, MgInstanceExtensionOptions.ALL); using (var scope = new SimpleInjector.Scope(container)) { var configuration = container.GetInstance <IMgGraphicsConfiguration>(); configuration.Initialize(0, 0); IKTXTextureLoader loader = container.GetInstance <IKTXTextureLoader>(); using (var fs = System.IO.File.OpenRead("1.ktx")) { var result = loader.Load(fs); } } } } } catch (Exception ex) { Console.WriteLine(ex); } }
protected override IServiceProvider BootstrapInternal(ILoggerFactory loggerFactory) { var container = new Container(); if (loggerFactory != null) { container.RegisterSingleton<ILoggerFactory>(loggerFactory); container.RegisterSingleton(typeof(ILogger<>), typeof(Logger<>)); } container.RegisterSingleton<ICacheClient>(() => new InMemoryCacheClient()); container.RegisterSingleton<ILockProvider>(() => new CacheLockProvider(container.GetInstance<ICacheClient>(), container.GetInstance<IMessageBus>(), loggerFactory)); return container; }
public static Container Bootstrap() { var assembly = Assembly.GetExecutingAssembly(); var container = new Container(); // Setup Quick Converter. QuickConverter.EquationTokenizer.AddNamespace(typeof(object)); QuickConverter.EquationTokenizer.AddNamespace("System", Assembly.GetAssembly(typeof(object))); QuickConverter.EquationTokenizer.AddNamespace(typeof(System.Windows.Visibility)); QuickConverter.EquationTokenizer.AddAssembly(Assembly.GetAssembly(typeof(System.Windows.Visibility))); container.Register<ISystemEnvironment, SystemEnvironment>(Lifestyle.Singleton); container.Register<IAppVisualThemeManager, AppVisualThemeManager>(Lifestyle.Singleton); container.Register<IProgramSettingsManager, ProgramSettingsManager>(Lifestyle.Singleton); container.Register<IApplication, WpfApplication>(Lifestyle.Singleton); container.Register<IViewProvider, ViewProvider>(Lifestyle.Singleton); container.Register<IDialogProvider, DialogProvider>(); container.Register<ICameraProvider, CameraProvider>(Lifestyle.Singleton); container.Register<ILogService, LogService>(Lifestyle.Singleton); container.Register<IStorageService, StorageService>(Lifestyle.Singleton); container.Register<ICameraService, CameraService>(Lifestyle.Singleton); container.Register<IImagingService, ImagingService>(Lifestyle.Singleton); container.Register<IImageIoService, ImageIoService>(Lifestyle.Singleton); container.Register<ITargetAduFinder, TargetAduFinder>(Lifestyle.Singleton); var viewModelTypes = GetAllTypesImplementingOpenGenericType(typeof (IViewModel<>), assembly).ToList(); viewModelTypes.ForEach(t => container.Register(t)); var viewTypes = GetAllTypesImplementingOpenGenericType(typeof (IView<>), assembly).ToList(); viewTypes.ForEach(t => container.Register(t)); var viewProvider = container.GetInstance<IViewProvider>(); viewProvider.Register<ConnectDialog, ConnectDialogViewModel>(); viewProvider.Register<DeviceInfoDialog, DeviceInfoViewModel>(); viewProvider.Register<HistogramDialog, HistogramDialogViewModel>(); viewProvider.Register<SessionDialog, SessionDialogViewModel>(); viewProvider.Register<TemperatureDialog, TemperatureDialogViewModel>(); viewProvider.Register<BiasFrameDialog, BiasFrameDialogViewModel>(); viewProvider.Register<DarkFrameDialog, DarkFrameDialogViewModel>(); viewProvider.Register<FlatFrameDialog, FlatFrameDialogViewModel>(); var imageIoService = container.GetInstance<IImageIoService>(); var fitsWriter = new FitsWriter(); imageIoService.RegisterImageWriter(fitsWriter.Format, fitsWriter); container.Verify(); return container; }
static void Main(string[] args) { Container container = new Container(); container.Register<ILogger, NerdAmigo.Abstractions.Default.DefaultLogger>(Lifestyle.Singleton); container.Register<IPathMapper, CliPathMapper>(Lifestyle.Singleton); container.Register(typeof(IConfigurationProvider<>), typeof(NerdAmigo.Common.Configuration.ConfigurationProvider<>), Lifestyle.Singleton); container.Register<IQueueIdentifierProvider, QueueIdentifierProvider>(Lifestyle.Singleton); container.Register(typeof(IQueueClient<>), typeof(SQSClient<>), Lifestyle.Singleton); container.Register(typeof(IQueueMessageWorker<>), new[] { System.Reflection.Assembly.GetExecutingAssembly() }); container.Register(typeof(QueueMessageProcessor<>), new[] { System.Reflection.Assembly.GetExecutingAssembly() }); container.RegisterDecorator(typeof(IQueueClient<>), typeof(QueueClientLogDecorator<>)); container.Verify(); IQueueClient<SampleMessage> queueClient = container.GetInstance<IQueueClient<SampleMessage>>(); using (CancellationTokenSource cts = new CancellationTokenSource()) { Task sender = Task.Factory.StartNew(() => { int idx = 0; Random r = new Random(); while (!cts.Token.IsCancellationRequested) { queueClient.Enqueue(new SampleMessage() { Name = DateTime.Now.ToShortTimeString(), Id = ++idx }, cts.Token); cts.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(r.Next(60))); } }, cts.Token); QueueMessageProcessor<SampleMessage> messageProcessor = container.GetInstance<QueueMessageProcessor<SampleMessage>>(); messageProcessor.QueueMessageWorkerActivator = new SimpleInjectorQueueMessageWorkerActivator(container); messageProcessor.Begin(cts.Token); Console.ReadKey(); cts.Cancel(); try { sender.Wait(); } catch (AggregateException ex) { foreach (Exception iEx in ex.InnerExceptions) { Console.WriteLine("Task Exception: " + iEx.Message); } } } }
public void SingletonRegister_Success() { ITestCase testCase = new TestCaseC(); var c = new Container(); c = (Container)testCase.SingletonRegister(c); var obj1 = c.GetInstance<ITestC>(); var obj2 = c.GetInstance<ITestC>(); Assert.AreEqual(obj1, obj2); Helper.Check(obj1, true); Helper.Check(obj2, true); }
public override void BeforeEverything() { Container = SimpleInjectorContainer.Container; fix_application_parameter_variables(Container); var config = Container.GetInstance<ChocolateyConfiguration>(); var force = config.Force; config.Force = true; unpack_self(Container,config); config.Force = force; base.BeforeEverything(); ConfigurationBuilder.set_up_configuration(new List<string>(), config, Container.GetInstance<IFileSystem>(), Container.GetInstance<IXmlService>(), null); }
private static void RegisterRepositories(Container container, DragonSecurityHmacSection settings) { container.RegisterWebApiRequest<IAppRepository>(() => { var dapperAppRepository = new DapperAppRepository(container.GetInstance<IDbConnection>(), settings.AppsTableName); return dapperAppRepository; }); container.RegisterWebApiRequest<IUserRepository>(() => { var dapperUserRepository = new DapperUserRepository(container.GetInstance<IDbConnection>(), settings.UsersTableName); return dapperUserRepository; }); }
public void TransientRegister_Success() { ITestCase testCase = new TestCaseC(); var c = new Container(); c = (Container)testCase.TransientRegister(c); var obj1 = c.GetInstance<ITestC>(); var obj2 = c.GetInstance<ITestC>(); Assert.AreNotEqual(obj1, obj2); Helper.Check(obj1, false); Helper.Check(obj2, false); }
static void Main(string[] args) { // Create a new container var container = new SimpleInjector.Container(); // Configure the container (Register) container.Register <LogConfiguration>(); container.Register <IAccount, AccountController>(); container.Collection.Register <ILogger>(typeof(ConsoleLogger), typeof(CompositeLogger)); container.Collection.Append <ILogger, FileLoger>(); var assemblies = new[] { typeof(ICommand <>).Assembly }; //container.Register(typeof(ICommand<>), assemblies); container.Collection.Register(assemblies); container.Register <IHandler <AHandler>, AHandler>(); container.Register <IHandler <BHandler>, BHandler>(); container.RegisterInitializer <IHandler>(hdl => hdl.ExecuteAsynchronously = true); container.Register <Transient>(Lifestyle.Transient); //container.Register<Scoped>(Lifestyle.Scoped); container.Register <Singleton1>(Lifestyle.Singleton); container.RegisterInstance(new Singleton2()); container.RegisterSingleton <Singleton3>(); // Solve: Cycling dependency container.RegisterInstance <IServiceProvider>(container); container.Register <ServiceFactory>(); container.Register <AService>(); container.Register <BService>(); // Verify the container (optional) container.Verify(); Console.WriteLine("Verified ====>"); // Retrieve instances from the container (Resolve) DemoRegisterInitializer(container); DemoChangeValue <Transient>(container); //DemoChangeValue<Scoped>(container); DemoChangeValue <Singleton1>(container); DemoChangeValue <Singleton2>(container); DemoChangeValue <Singleton3>(container); var depenOnB = container.GetInstance <AService>(); var depenOnA = container.GetInstance <BService>(); }
private static void Run(this SimpleInjector.Container container) { var controller = container.GetInstance <CustomerController>(); var repository = container.GetInstance <ICustomerRepository>(); repository.Dump(); controller.MoveCustomer(new MoveCustomerCommand { CustomerId = "1", NewLocation = "Ohio" }); repository.Dump(); }
private static void InitializeContainer(Container container) { // Azure storage account container.Register(() => { var connectionString = ConfigurationManager.ConnectionStrings["AzureStorage"].ConnectionString; return CloudStorageAccount.Parse(connectionString); }); // Azure table client container.Register(() => container.GetInstance<CloudStorageAccount>().CreateCloudTableClient()); // TableSet for comments container.Register<ITableSet<Issue>>(() => new TableSet<Issue>(container.GetInstance<CloudTableClient>())); }
static void Main(string[] args) { Console.WriteLine("DEMO >> DbSet"); var contenedor = new SimpleInjector.Container(); contenedor.Register <IConeccion, Coneccion>(Lifestyle.Singleton); contenedor.Register <Productos>(Lifestyle.Singleton); var productos = contenedor.GetInstance <Productos>(); var a = productos.Crear(); a.Descripcion = "Coca cola"; a.Precio = 90; productos.Agregar(a); Pausa(); a.PonerOferta(); productos.Actualizar(a); Pausa(); productos.Borrar(a); Pausa(); var ps = productos.Traer("Precio < 90"); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); CriarContainerInjecaoDependencia(); Application.Run(container.GetInstance <Form1>()); }
private async void bindingNavigatorAddNewItem_Click(object sender, EventArgs e) { if (container.GetInstance <frm_AddEdit>().ShowDialog() == DialogResult.OK) { tblUsersBindingSource.DataSource = await usersService.SeletAllRecord(); } }
public void StartModule(Container container) { ILog log = LogUtils.GetLog(this); log.Debug("Starting Module Demo"); log.Debug("Registering menu item"); container.GetInstance<IMenuService>().RegisterMenu(new List<IMenuItemSecure>() { new SimpleMenuItem("Demo Option", "ModuleA", "Module Demo", "ctrl/ModuleDemo/DemoOption",new List<Role>()) }); container.GetInstance<IRouteService>().RegisterRoute(new RouteItem("ctrl/ModuleDemo/DemoOption", "ModuleA/DemoController",new List<Role>())); log.Debug("Module Demo start completed"); }
public void SimpleInjectorAdapter_Register_Always_Works() { var container = new Container(); var adapter = SimpleInjectorAdapter.Create(container); adapter.RegisterTransient<IMyInterface, MyClass>(); object result1 = container.GetInstance<IMyInterface>(); result1.Should().NotBeNull(); object result2 = container.GetInstance<IMyInterface>(); result2.Should().NotBeNull(); result1.Should().BeOfType<MyClass>(); result1.Should().NotBe(result2, "registraton was for a transient, not a singleton"); }
protected Scope InitializeFact(bool isUsingInMemoryDatabase = true) { Scope scope = null; lock (TestThreadLocker) { int threadId = System.Threading.Thread.CurrentThread.ManagedThreadId; InitializeContainer(threadId); if (isUsingInMemoryDatabase) { container.Register <IAppDbContext, TestAppDbContext>(Lifestyle.Scoped); container.Register <IThumbnailDbContext, TestThumbnailDbContext>(Lifestyle.Scoped); } else { container.Register <IAppDbContext, AppDbContext>(Lifestyle.Scoped); container.Register <IThumbnailDbContext, ThumbnailDbContext>(Lifestyle.Scoped); } container.Verify(); scope = AsyncScopedLifestyle.BeginScope(container); var context = (AppDbContext)container.GetInstance <IAppDbContext>(); if (isUsingInMemoryDatabase) { // In-Memory Database context.Database.OpenConnection(); context.Database.EnsureCreated(); } var app = (ApplicationContextImpl)container.GetInstance <IApplicationContext>(); app.Initialize(); System.Console.WriteLine("アプリケーションフォルダ=" + app.ApplicationDirectoryPath); ImportInitializeData(threadId, container); System.Console.WriteLine("データベースの初期化を完了しました。"); } return(scope); }
/// <summary>Resolves a single registered service.</summary> /// <typeparam name="TServiceType"><see cref="System.Type" /> of the requested service.</typeparam> /// <returns>The requested service.</returns> public override TServiceType GetService <TServiceType>() { var serviceType = typeof(TServiceType); // if (!typeof(WebViewPage).IsAssignableFrom(serviceType) /*&& (container.GetAllInstances<TServiceType>().Any() || container.Registrations.Any(registration => registration.MappedToType == typeof(TServiceType)))*/) // { return((TServiceType)container.GetInstance(serviceType)); //if (instances.Any()) //{ // return instances.FirstOrDefault(); //} //return container.Resolve<TServiceType>(); // } // return container.GetInstance<TServiceType>(); }
/// <summary> /// First time executed takes an expected hit on EF Core side. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void GetCustomerByIdentifierButton_Click(object sender, EventArgs e) { /* * See https://simpleinjector.readthedocs.io/en/latest/lifetimes.html?highlight=beginscope */ using (AsyncScopedLifestyle.BeginScope(CustomerContainer)) { var customerInstance = CustomerContainer.GetInstance <ICustomer>(); var customer = customerInstance.GetById(2); if (customer != null) { // ReSharper disable once LocalizableElement MessageBox.Show($"Company name {customer.CompanyName}"); } } }
/// <summary> /// Creates the specified controller context. /// </summary> /// <param name="controllerContext">The controller context.</param> /// <param name="type">The type.</param> /// <returns></returns> public object Create(ControllerContext controllerContext, Type type) { if (type == null) { return(null); } return(container.GetInstance(type)); }
public static void AddSlackNet(this Container container, Action <SimpleInjectorSlackHandlerConfiguration> configure = null) { var config = new SimpleInjectorSlackHandlerConfiguration(container); configure?.Invoke(config); container.RegisterFallbackType <ISlackServiceFactory, SimpleInjectorSlackServiceFactory>(Lifestyle.Singleton); container.RegisterFallback(() => new HttpClient(), Lifestyle.Singleton); container.RegisterFallback(() => Default.Http(container.GetInstance <SlackJsonSettings>(), container.GetInstance <HttpClient>), Lifestyle.Singleton); container.RegisterFallback(() => Default.UrlBuilder(container.GetInstance <SlackJsonSettings>()), Lifestyle.Singleton); container.RegisterFallback(() => Default.JsonSettings(container.GetInstance <ISlackTypeResolver>()), Lifestyle.Singleton); container.RegisterFallback(() => Default.SlackTypeResolver(Default.AssembliesContainingSlackTypes), Lifestyle.Singleton); container.RegisterFallback(() => Default.WebSocketFactory, Lifestyle.Singleton); container.RegisterFallback(() => Default.Scheduler, Lifestyle.Singleton); container.RegisterFallbackType <ISlackRequestListener, SimpleInjectorSlackRequestListener>(Lifestyle.Singleton); container.RegisterFallbackType <ISlackHandlerFactory, SimpleInjectorSlackHandlerFactory>(Lifestyle.Singleton); container.RegisterFallback(() => config.HandlerIndex <IBlockOptionProvider>(), Lifestyle.Singleton); container.RegisterFallback(() => config.HandlerIndex <IAsyncViewSubmissionHandler>(), Lifestyle.Singleton); container.RegisterFallback(() => config.HandlerIndex <IAsyncSlashCommandHandler>(), Lifestyle.Singleton); container.RegisterFallback(() => config.HandlerIndex <IInteractiveMessageHandler>(), Lifestyle.Singleton); container.RegisterFallback(() => config.HandlerIndex <IOptionProvider>(), Lifestyle.Singleton); container.RegisterFallback(() => config.HandlerIndex <IDialogSubmissionHandler>(), Lifestyle.Singleton); // We need to resolve collections of these handlers, but SimpleInjector requires at least one registration. container.RegisterFallbackCollection <IEventHandler>(); container.RegisterFallbackCollection <IAsyncBlockActionHandler>(); container.RegisterFallbackCollection <IAsyncMessageShortcutHandler>(); container.RegisterFallbackCollection <IAsyncGlobalShortcutHandler>(); container.RegisterFallbackCollection <IAsyncWorkflowStepEditHandler>(); container.RegisterFallbackType <IEventHandler, CompositeEventHandler>(Lifestyle.Scoped); container.RegisterFallbackType <IAsyncBlockActionHandler, CompositeBlockActionHandler>(Lifestyle.Scoped); container.RegisterFallbackType <IBlockOptionProvider, SwitchingBlockOptionProvider>(Lifestyle.Scoped); container.RegisterFallbackType <IAsyncMessageShortcutHandler, CompositeMessageShortcutHandler>(Lifestyle.Scoped); container.RegisterFallbackType <IAsyncGlobalShortcutHandler, CompositeGlobalShortcutHandler>(Lifestyle.Scoped); container.RegisterFallbackType <IOptionProvider, SwitchingOptionProvider>(Lifestyle.Scoped); container.RegisterFallbackType <IAsyncViewSubmissionHandler, SwitchingViewSubmissionHandler>(Lifestyle.Scoped); container.RegisterFallbackType <IAsyncSlashCommandHandler, SwitchingSlashCommandHandler>(Lifestyle.Scoped); container.RegisterFallbackType <IInteractiveMessageHandler, SwitchingInteractiveMessageHandler>(Lifestyle.Scoped); container.RegisterFallbackType <IDialogSubmissionHandler, SwitchingDialogSubmissionHandler>(Lifestyle.Scoped); container.RegisterFallbackType <IAsyncWorkflowStepEditHandler, CompositeWorkflowStepEditHandler>(Lifestyle.Scoped); container.RegisterFallback <ISlackApiClient>(() => new SlackApiClient(container.GetInstance <IHttp>(), container.GetInstance <ISlackUrlBuilder>(), container.GetInstance <SlackJsonSettings>(), config.ApiToken), Lifestyle.Singleton); container.RegisterFallback <ICoreSocketModeClient>(() => new CoreSocketModeClient( container.GetInstance <ISlackApiClient>().WithAccessToken(config.AppLevelToken), container.GetInstance <IWebSocketFactory>(), container.GetInstance <SlackJsonSettings>(), container.GetInstance <IScheduler>()), Lifestyle.Singleton); container.RegisterFallbackType <ISlackSocketModeClient, SlackSocketModeClient>(Lifestyle.Singleton); }
private void RegisterAllDependenciesForInMemoryDependencyResolver(SimpleInjector.Container container) { var inMemoryEventRouter = new InMemoryEventRouter(); var inMemoryCommandRouter = new InMemoryCommandRouter(); container.Register <ICommandSubscriber>(() => inMemoryCommandRouter, Lifestyle.Singleton); container.Register <ICommandPublisher>(() => inMemoryCommandRouter, Lifestyle.Singleton); container.Register <IEventPublisher>(() => inMemoryEventRouter, Lifestyle.Singleton); container.Register <IEventSubscriber>(() => inMemoryEventRouter, Lifestyle.Singleton); container.Register <IEventStore>(() => new InMemoryEventStore(container.GetInstance <IEventPublisher>()), Lifestyle.Singleton); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (Bootstrap()) { Cursor.Current = Cursors.Default; Application.Run(container.GetInstance <TopXConverter>()); } Cursor.Current = Cursors.Default; }
public static void RegisterSingleInterfacesAndType <T>(this Container container, IEnumerable <Type> types) { var ifaceType = typeof(T); foreach (var s in types) { container.RegisterSingle(s, s); foreach (var i in s.GetInterfaces().Where(x => Predicate(x, ifaceType))) { container.RegisterSingle(i, () => container.GetInstance(s)); } } }
public void TestMethod1() { try { var container = new SimpleInjector.Container(); ImagemSimplesWeb.Application.AutoMapper.AutoMapperConfig.RegisterMappings(); ImagemSimplesWeb.Infra.CrossCutting.IoC.BootStrapper.RegisterServices(container); var teste = container.GetInstance <IUser_CadastroService>(); var teste2 = teste.BuscarTodos(); } catch (Exception ex) { Console.Write(ex.GetBaseException().Message); } }
public static void Main(string[] args) { try { var cnt = new SimpleInjector.Container(); PackageExtensions.RegisterPackages(cnt, System.AppDomain.CurrentDomain.GetAssemblies()); // //var options = new OptionSet { // { "instance=", "append a tag onto the instance name, to allow multiple services to run", (string r) => cfg.ApplicationInstanceId = r }, //}; //var test = options.Parse(args); HostFactory.Run(c => { var cfg = cnt.GetInstance <IConfiguration>(); c.UseSimpleInjector(cnt); // TODO: Will need to change this to run as user later... c.RunAsLocalSystem(); var instanceOverride = cfg.ApplicationInstanceName; var serviceDisplayName = string.Format("{0} - {1}", cfg.ApplicationName, instanceOverride); var serviceName = string.Format("{0} - {1}", cfg.ApplicationName, instanceOverride); var serviceDescription = string.Format("{0} - {1}", cfg.ApplicationName, instanceOverride); c.SetDisplayName(serviceDisplayName); c.SetServiceName(serviceName); c.SetDescription(serviceDescription); c.EnableServiceRecovery(rc => { rc.RestartService(1); // restart the service after 1 minute rc.RestartService(2); // restart the service after 2 minute rc.RestartService(3); // restart the service after 3 minute rc.SetResetPeriod(1); // set the reset interval to one day }); c.Service <ISecureBootstrapListenerService>(srv => { srv.ConstructUsingSimpleInjector(); srv.WhenStarted((service) => service.Start()); srv.WhenStopped((service) => service.Stop()); }); }); } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message} at {ex.StackTrace}"); } }
public void CallTest() { var spCont = new SimpleInjector.Container(); spCont.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); spCont.Register <ICentralConfigProvider, TestConfigProvider>(Lifestyle.Scoped); AsyncScopedLifestyle.BeginScope(spCont); spCont.GetInstance <ICentralConfigProvider>(); Lifestyle.Scoped.GetCurrentScope(spCont)?.Dispose(); Console.WriteLine("Dispose scope."); Console.WriteLine("CallTest End--------------------"); }
public App() { InitializeComponent(); var userSelectedCulture = new CultureInfo("fr-FR"); Thread.CurrentThread.CurrentCulture = userSelectedCulture; if (_startup == null) { _startup = new Startup(); _startup.ConfigureServices(_container); } AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; MainPage = _container.GetInstance <Cbl2Db22RepTest.MainPage>(); }
/// <summary> /// ユニットテスト用のSQLファイルを読み込む /// </summary> void ImportSqlFile(SimpleInjector.Container container, string ImportSqlFileName) { string sqltext = ""; System.Reflection.Assembly assm = System.Reflection.Assembly.GetExecutingAssembly(); using (var stream = assm.GetManifestResourceStream(string.Format("Pixstock.Nc.Srv.Tests.Assets.Sql.{0}", ImportSqlFileName))) { using (StreamReader reader = new StreamReader(stream)) { sqltext = reader.ReadToEnd(); } } if (!string.IsNullOrEmpty(sqltext)) { var @dbc = (AppDbContext)container.GetInstance <IAppDbContext>(); @dbc.Database.ExecuteSqlCommand(sqltext); @dbc.SaveChanges(); } }
static IMediator BuildMediator() { var container = new SimpleInjector.Container(); // Mediator container.RegisterSingleton <IMediator, Mediator>(); container.Register(() => new ServiceFactory(container.GetInstance), Lifestyle.Singleton); // Handlers var assemblies = new[] { typeof(RequestAsync).Assembly }; container.Register(typeof(IRequestHandler <,>), assemblies); container.Collection.Register(typeof(INotificationHandler <>), assemblies); // Pipeline behaviours container.Collection.Register(typeof(IPipelineBehavior <,>), new[] { typeof(GenericPipelineBehavior <,>) // optionals can be register in this line. }); // ------ Optionals ------ // Pre processor container.Collection.Append(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>)); container.Collection.Register(typeof(IRequestPreProcessor <>), new[] { typeof(GenericRequestPreProcessor <>) }); // Post processor container.Collection.Append(typeof(IPipelineBehavior <,>), typeof(RequestPostProcessorBehavior <,>)); container.Collection.Register(typeof(IRequestPostProcessor <,>), new[] { typeof(GenericRequestPostProcessor <,>) }); container.Verify(); var mediator = container.GetInstance <IMediator>(); return(mediator); }
/// <summary> /// データベースに関する初期化処理 /// </summary> private void InitializeAppDatabase() { AppMetaInfo apMetadata = null; bool isMigrate = false; const string appdb_structure_version_key = "APPDB_VER"; var @dbc = (AppDbContext)mContainer.GetInstance <IAppDbContext>(); // DIコンテナがリソースの開放を行う bool isInitializeDatabase = false; var @repo = new AppAppMetaInfoRepository(@dbc); try { apMetadata = @repo.FindBy(p => p.Key == appdb_structure_version_key).FirstOrDefault(); if (apMetadata == null) { isInitializeDatabase = true; } } catch (Exception) { isInitializeDatabase = true; } if (isInitializeDatabase) { // データベースにテーブルなどの構造を初期化する string sqltext = ""; System.Reflection.Assembly assm = System.Reflection.Assembly.GetExecutingAssembly(); string filePath = string.Format("Pixstock.Service.Web.Assets.Sql.{0}.Initialize_sql.txt", "App"); using (var stream = assm.GetManifestResourceStream(filePath)) { using (StreamReader reader = new StreamReader(stream)) { sqltext = reader.ReadToEnd(); } } _logger.Info("SQLファイル({FilePath})から、CREATEを読み込みます", filePath); @dbc.Database.ExecuteSqlCommand(sqltext); @dbc.SaveChanges(); // 初期データを格納する var repo_Category = new CategoryRepository(@dbc); repo_Category.Add(new Category { Id = 1L, Name = "ROOT" }); apMetadata = @repo.FindBy(p => p.Key == appdb_structure_version_key).FirstOrDefault(); } if (apMetadata == null) { apMetadata = new AppMetaInfo { Key = appdb_structure_version_key, Value = "1.0.0" }; @repo.Add(apMetadata); @repo.Save(); // AppMetadataが存在しない場合のみ、初期値の書き込みを行う。 // 初期値は、キッティングから取得したリソースパスが示すSQLファイルからデータベースの初期値を読み込む。 if (this._AssemblyParameter.Params.ContainsKey("InitializeSqlAppDb")) { System.Reflection.Assembly assm = System.Reflection.Assembly.GetExecutingAssembly(); var initializeSqlFilePath = this._AssemblyParameter.Params["InitializeSqlAppDb"]; _logger.Info($"アプリケーションデータベース初期化SQLファイルを読み込みます path:{initializeSqlFilePath}"); string sqltext = ""; using (var stream = assm.GetManifestResourceStream(initializeSqlFilePath)) { using (StreamReader reader = new StreamReader(stream)) { sqltext = reader.ReadToEnd(); } } @dbc.Database.ExecuteSqlCommand(sqltext); @dbc.SaveChanges(); } } string currentVersion = apMetadata.Value; string nextVersion = currentVersion; do { currentVersion = nextVersion; nextVersion = UpgradeFromResource("App", currentVersion, @dbc); if (nextVersion != currentVersion) { isMigrate = true; } } while (nextVersion != currentVersion); if (isMigrate) { apMetadata.Value = nextVersion; @repo.Save(); } @dbc.SaveChanges(); }
public T Resolve <T>() where T : class { return(_container.GetInstance <T>()); }
public object Resolve(Type resolve) { return(_container.GetInstance(resolve)); }
public void Execute(IJobExecutionContext context) { using (_container.BeginLifetimeScope()) { var config = EmailConfiguration.GetConfig(); var loggerFactory = _container.GetInstance <ILoggerFactory>(); ILogger logger = loggerFactory.GetLogger("Scheduler"); var errorFileList = new List <MovedFileOutput>(); try { logger.Info("Reading XML Monthly start on " + DateTime.Now); errorFileList.AddRange(_svc.Run(SchedulerEnums.Schedule.MonthLy)); foreach (var errorFile in errorFileList) { logger.Warn(String.Format("Error on files : {0}", errorFile.FileName)); var body = String.Format("Error on files : {0}", errorFile.FileName); foreach (var error in errorFile.ErrorList) { logger.Info(String.Format(error)); body += String.Format("<p>{0}</p>", error); } logger.Error(EmailUtility.Email(body, null)); } logger.Info("Reading XML Minthly ended On " + DateTime.Now); } catch (Exception ex) { logger.Error("Reading XML crashed", ex); var body = String.Format("<p>{0}</p>", ex.Message); body += String.Format("<p>{0}</p>", ex.StackTrace); if (!String.IsNullOrEmpty(body)) { logger.Error(EmailUtility.Email(body, "Scheduler is down")); } } //if (errorList.Count > 0) //{ // foreach (var err in errorList) // { // logger.Info(err); // } // //errorList.Insert(0,_svc.filesMoved.); // var body = StringErrorList(errorList); // logger.Error(EmailUtility.Email(body, null)); //} if (errorFileList.Count == 0) { var body = string.Empty; if (_svc.filesMoved.Count > 0) { foreach (var file in _svc.filesMoved) { string info = String.Format("<p>XML file {0} : {1}</p>" , file.IsError ? "Error" : "Archieved" , file.FileName); if (file.IsError) { body += info; } logger.Info(info); } if (!String.IsNullOrEmpty(body)) { logger.Error(EmailUtility.Email(body, null)); } } } } }
public object GetInstance(Type type) { return(_container.GetInstance(type)); }
public TContract GetInstance <TContract>() where TContract : class { return(_container.GetInstance <TContract>()); }
/// <summary> /// Loads the module into the kernel. /// </summary> public void RegisterComponents(SimpleInjector.Container container) { IConfiguration configuration = new Configuration(); container.Register <IConfiguration>(() => configuration, Lifestyle.Singleton); Lazy <GallerySetting> gallerySetting = new Lazy <GallerySetting>(() => { using (var entitiesContext = new EntitiesContext()) { var settingsRepo = new EntityRepository <GallerySetting>(entitiesContext); return(settingsRepo.GetAll().FirstOrDefault()); } }); container.Register <GallerySetting>(() => gallerySetting.Value); //Bind<GallerySetting>().ToMethod(c => gallerySetting.Value); container.RegisterPerWebRequest <ISearchService, LuceneSearchService>(); container.RegisterPerWebRequest <IEntitiesContext>(() => new EntitiesContext()); container.RegisterPerWebRequest <IEntityRepository <User>, EntityRepository <User> >(); container.RegisterPerWebRequest <IEntityRepository <PackageRegistration>, EntityRepository <PackageRegistration> >(); container.RegisterPerWebRequest <IEntityRepository <Package>, EntityRepository <Package> >(); container.RegisterPerWebRequest <IEntityRepository <PackageAuthor>, EntityRepository <PackageAuthor> >(); container.RegisterPerWebRequest <IEntityRepository <PackageFramework>, EntityRepository <PackageFramework> >(); container.RegisterPerWebRequest <IEntityRepository <PackageDependency>, EntityRepository <PackageDependency> >(); container.RegisterPerWebRequest <IEntityRepository <PackageFile>, EntityRepository <PackageFile> >(); container.RegisterPerWebRequest <IEntityRepository <PackageStatistics>, EntityRepository <PackageStatistics> >(); container.RegisterPerWebRequest <IEntityRepository <PackageOwnerRequest>, EntityRepository <PackageOwnerRequest> >(); container.RegisterPerWebRequest <IUserService, UserService>(); container.RegisterPerWebRequest <IPackageService, PackageService>(); container.RegisterPerWebRequest <ICryptographyService, CryptographyService>(); container.Register <IFormsAuthenticationService, FormsAuthenticationService>(Lifestyle.Singleton); container.RegisterPerWebRequest <IControllerFactory, NuGetControllerFactory>(); container.RegisterPerWebRequest <IIndexingService, LuceneIndexingService>(); container.RegisterPerWebRequest <INuGetExeDownloaderService, NuGetExeDownloaderService>(); Lazy <IMailSender> mailSenderThunk = new Lazy <IMailSender>(() => { var settings = container.GetInstance <GallerySetting>(); if (settings.UseSmtp) { var mailSenderConfiguration = new MailSenderConfiguration() { DeliveryMethod = SmtpDeliveryMethod.Network, Host = settings.SmtpHost, Port = settings.SmtpPort, EnableSsl = configuration.SmtpEnableSsl, }; if (!String.IsNullOrWhiteSpace(settings.SmtpUsername)) { mailSenderConfiguration.UseDefaultCredentials = false; mailSenderConfiguration.Credentials = new NetworkCredential( settings.SmtpUsername, settings.SmtpPassword); } return(new NuGetGallery.MailSender(mailSenderConfiguration)); } else { var mailSenderConfiguration = new MailSenderConfiguration() { DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory, PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail") }; return(new NuGetGallery.MailSender(mailSenderConfiguration)); } }); container.Register <IMailSender>(() => mailSenderThunk.Value, Lifestyle.Singleton); container.Register <IMessageService, MessageService>(Lifestyle.Singleton); container.RegisterPerWebRequest <IPrincipal>(() => HttpContext.Current.User); //Bind<IPrincipal>().ToMethod(context => HttpContext.Current.User); switch (configuration.PackageStoreType) { case PackageStoreType.FileSystem: case PackageStoreType.NotSpecified: container.Register <IFileSystemService, FileSystemService>(Lifestyle.Singleton); container.Register <IFileStorageService, FileSystemFileStorageService>(Lifestyle.Singleton); break; case PackageStoreType.AzureStorageBlob: container.Register <ICloudBlobClient>(() => new CloudBlobClientWrapper(new CloudBlobClient( new Uri(configuration.AzureStorageBlobUrl, UriKind.Absolute), new StorageCredentialsAccountAndKey(configuration.AzureStorageAccountName, configuration.AzureStorageAccessKey) )) , Lifestyle.Singleton); container.Register <IFileStorageService, CloudBlobFileStorageService>(Lifestyle.Singleton); break; case PackageStoreType.AmazonS3Storage: container.Register <IAmazonS3Client, AmazonS3ClientWrapper>(Lifestyle.Singleton); container.Register <IFileStorageService, AmazonS3FileStorageService>(Lifestyle.Singleton); break; } container.Register <IPackageFileService, PackageFileService>(Lifestyle.Singleton); container.Register <IUploadFileService, UploadFileService>(); // todo: bind all package curators by convention container.Register <IAutomaticPackageCurator, WebMatrixPackageCurator>(Lifestyle.Singleton); container.Register <IAutomaticPackageCurator, Windows8PackageCurator>(Lifestyle.Singleton); // todo: bind all commands by convention container.RegisterPerWebRequest <IAutomaticallyCuratePackageCommand, AutomaticallyCuratePackageCommand>(); container.RegisterPerWebRequest <ICreateCuratedPackageCommand, CreateCuratedPackageCommand>(); container.RegisterPerWebRequest <IDeleteCuratedPackageCommand, DeleteCuratedPackageCommand>(); container.RegisterPerWebRequest <IModifyCuratedPackageCommand, ModifyCuratedPackageCommand>(); // todo: bind all queries by convention container.RegisterPerWebRequest <ICuratedFeedByKeyQuery, CuratedFeedByKeyQuery>(); container.RegisterPerWebRequest <ICuratedFeedByNameQuery, CuratedFeedByNameQuery>(); container.RegisterPerWebRequest <ICuratedFeedsByManagerQuery, CuratedFeedsByManagerQuery>(); container.RegisterPerWebRequest <IPackageRegistrationByKeyQuery, PackageRegistrationByKeyQuery>(); container.RegisterPerWebRequest <IPackageRegistrationByIdQuery, PackageRegistrationByIdQuery>(); container.RegisterPerWebRequest <IUserByUsernameQuery, UserByUsernameQuery>(); container.RegisterPerWebRequest <IPackageIdsQuery, PackageIdsQuery>(); container.RegisterPerWebRequest <IPackageVersionsQuery, PackageVersionsQuery>(); container.RegisterPerWebRequest <IAggregateStatsService, AggregateStatsService>(); RegisterChocolateySpecific(container); }
public TInstance GetInstance <TInstance>() where TInstance : class { return(_container.GetInstance <TInstance>()); }