public IEnumerable<IValidationDefinition> GetModules() { IKernel kernel = new StandardKernel(); kernel.Load(Assembly.GetExecutingAssembly()); var modules = kernel.GetAll<IValidationDefinition>().ToList(); return modules; }
static void Main(string[] args) { var kernel = new StandardKernel(); BuildDependencies(kernel); var commandReaders = kernel.GetAll<ICommandReader>().ToList(); bool exit = false; while (!exit) { var command = Console.ReadLine(); if (command == "exit" || command == "quit") { exit = true; continue; } foreach (var commandReader in commandReaders) { if (!commandReader.Validate(command)) { continue; } commandReader.Process(command); break; } } }
public static void RegisterDependenciesViaNinject(HttpConfiguration httpConfiguration) { var kernel = new StandardKernel(); kernel.Bind<IWordRepository>().To<WordRepository>(); kernel.Bind<IMeaningRepository>().To<MeaningRepository>(); httpConfiguration.ServiceResolver.SetResolver( t => kernel.TryGet(t), t => kernel.GetAll(t)); }
public static void Configure(HttpConfiguration config) { config.Filters.Add(new ValidationActionFilter()); var kernel = new StandardKernel(); kernel.Bind<ISlechRepository>().ToConstant(new InitialData()); config.ServiceResolver.SetResolver( t => kernel.TryGet(t), t => kernel.GetAll(t)); }
public MainWindow() { InitializeComponent(); IKernel kernel = new StandardKernel(); LibraryLoader.LoadAllBinDirectoryAssemblies(); if (File.Exists("TypeMappings.xml")) kernel.Load("TypeMappings.xml"); var plugins = kernel.GetAll<IPlugin>().ToList(); PluginsListView.ItemsSource = plugins; }
static void Main(string[] args) { IKernel kernel = new StandardKernel(new OrmConfigurationModule(), new HarnessModule()); var config = kernel.Get<IRunnerConfig>(); List<List<ScenarioResult>> allRunResults = new List<List<ScenarioResult>>(); for (int i = 0; i < config.NumberOfRuns; i++) { Console.WriteLine(String.Format("Starting run number {0} at {1}", i, DateTime.Now.ToShortTimeString())); allRunResults.Add(kernel.Get<ScenarioRunner>().Run(config.MaximumSampleSize)); } var compiledResults = new List<CompiledScenarioResult>(); foreach (var result in allRunResults[0]) { var results = from set in allRunResults from res in set where res.ConfigurationName == result.ConfigurationName where res.SampleSize == result.SampleSize where res.ScenarioName == result.ScenarioName where res.Technology == result.Technology select res; compiledResults.Add(new CompiledScenarioResult { ConfigurationName = result.ConfigurationName, SampleSize = result.SampleSize, ScenarioName = result.ScenarioName, Technology = result.Technology, MinSetupTime = results.OrderBy(r => r.SetupTime).Take(results.Count() - config.DiscardWorst).Min(r=>r.SetupTime), AverageSetupTime = results.OrderBy(r => r.SetupTime).Take(results.Count() - config.DiscardWorst).Average(r => r.SetupTime), MaxSetupTime = results.OrderBy(r => r.SetupTime).Take(results.Count() - config.DiscardWorst).Max(r => r.SetupTime), MinApplicationTime = results.OrderBy(r => r.ApplicationTime).Take(results.Count() - config.DiscardWorst).Min(r => r.ApplicationTime), AverageApplicationTime = results.OrderBy(r => r.ApplicationTime).Take(results.Count() - config.DiscardWorst).Average(r => r.ApplicationTime), MaxApplicationTime = results.OrderBy(r => r.ApplicationTime).Take(results.Count() - config.DiscardWorst).Max(r => r.ApplicationTime), MinCommitTime = results.OrderBy(r => r.CommitTime).Take(results.Count() - config.DiscardWorst).Min(r => r.CommitTime), AverageCommitTime = results.OrderBy(r => r.CommitTime).Take(results.Count() - config.DiscardWorst).Average(r => r.CommitTime), MaxCommitTime = results.OrderBy(r => r.CommitTime).Take(results.Count() - config.DiscardWorst).Max(r => r.CommitTime), Status = results.OrderByDescending(r => (int) r.Status.State).Select(r=> r.Status).FirstOrDefault() ?? new AssertionPass(), MemoryUsage = results.Count() > config.DiscardWorst + config.DiscardHighestMemory ? results.OrderBy(r => r.MemoryUsage).Take(results.Count() - config.DiscardWorst) .OrderByDescending(r => r.MemoryUsage).Take(results.Count() - config.DiscardWorst -config.DiscardHighestMemory).Average(r => r.MemoryUsage) : results.Average(r=>r.MemoryUsage) }); } foreach (var formatter in kernel.GetAll<IResultFormatter<CompiledScenarioResult>>()) { formatter.FormatResults(compiledResults); } Console.ReadLine(); }
public ThreadedPerformanceSessionControl() { InitializeComponent(); _testUrls = new List<string>(); IKernel kernel = new StandardKernel(); LibraryLoader.LoadAllBinDirectoryAssemblies(); if (File.Exists("TypeMappings.xml")) kernel.Load("TypeMappings.xml"); var plugins = kernel.GetAll<IThreadedPerformanceSessionTestUrlGenerator>().ToList(); UrlGeneratorPlugins.ItemsSource = plugins.ToList(); }
public static void Main(string[] args) { var kernel = new StandardKernel(); kernel.Load<TychaiaGlobalIoCModule>(); kernel.Load<TychaiaProceduralGenerationIoCModule>(); kernel.Load<TychaiaToolIoCModule>(); ConsoleCommandDispatcher.DispatchCommand( kernel.GetAll<ConsoleCommand>(), args, Console.Out); }
public static void Main(string[] args) { var kernel = new StandardKernel(); kernel.Bind<IRenderDemo>().To<SingleCubeDemo>(); kernel.Bind<IRenderDemo>().To<UncachedChunkDemo>(); kernel.Bind<IRenderDemo>().To<EverythingDemo>(); using (var game = new PerspectiveGame(kernel.GetAll<IRenderDemo>())) { game.Run(); } }
/// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); DependencyResolver.SetResolver(t => kernel.TryGet(t), t => kernel.GetAll(t)); GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); return kernel; }
public void CanGetAllValidators() { IKernel kernel = new StandardKernel(); kernel.Scan(scanner => { scanner.From(typeof(IValidator).Assembly); scanner.WhereTypeInheritsFrom<IValidator>(); scanner.BindWith<NinjectServiceToInterfaceBinder>(); }); var validators = kernel.GetAll<IValidator>(); Assert.IsNotNull(validators); Assert.AreEqual(3, validators.Count()); }
public static void Configure(HttpConfiguration config) { config.Routes.MapHttpRoute("def", "bugs/{controller}", new {controller = "Index"}); config.Formatters.Add(new RazorHtmlMediaTypeFormatter()); config.MessageHandlers.Add(new EtagMessageHandler()); var kernel = new StandardKernel(); kernel.Bind<IBugRepository>().To<StaticBugRepository>(); config.ServiceResolver.SetResolver(t => kernel.TryGet(t), t => kernel.GetAll(t)); AutoMapperConfig.Configure(); }
public AugmentationTests() { var container = new Ninject.StandardKernel(); container.Bind(x => x.FromAssemblyContaining(typeof(IAugmentViewModels)) .SelectAllClasses() .InheritedFrom <IAugmentViewModels>() .BindAllInterfaces() ); var services = container.GetAll <IAugmentViewModels>(); _sut = new UberService(services); }
public void CanFilterOutValidatorRegistrations() { IKernel kernel = new StandardKernel(); kernel.Scan(scanner => { scanner.From(typeof(IValidator).Assembly); scanner.WhereTypeInheritsFrom<IValidator>(); // excluding the FailValidator should leave 2 of them scanner.Where(t => t != typeof(FailValidator)); scanner.BindWith<NinjectServiceToInterfaceBinder>(); }); var validators = kernel.GetAll<IValidator>(); Assert.IsNotNull(validators); Assert.AreEqual(2, validators.Count()); }
public static void Main(string[] args) { var kernel = new StandardKernel(new Bindings()); new Service(args, ()=> kernel.GetAll<IWindowsService>().ToArray(), installationSettings: (serviceInstaller, serviceProcessInstaller) => { serviceInstaller.ServiceName = "OpenSonos.LocalMusicServer.Service"; serviceInstaller.StartType = ServiceStartMode.Automatic; serviceProcessInstaller.Account = ServiceAccount.NetworkService; }, configureContext: x => { x.Log = Console.WriteLine; }, registerContainer: () => new SimpleServicesToNinject(kernel)) .Host(); }
private static HttpSelfHostServer SetupWebApiServer(string url) { var ninjectKernel = new StandardKernel(); ninjectKernel.Bind<IContactRepository>().To<InMemoryContactRepository>(); var configuration = new HttpSelfHostConfiguration(url); configuration.ServiceResolver.SetResolver( t => ninjectKernel.TryGet(t), t => ninjectKernel.GetAll(t)); configuration.Routes.MapHttpRoute( "Default", "{controller}/{id}/{ext}", new {id = RouteParameter.Optional, ext = RouteParameter.Optional}); var host = new HttpSelfHostServer(configuration); return host; }
private static void LoadModules() { var kernel = new StandardKernel(); kernel.Bind(c => c.FromAssembliesInPath("./") .SelectAllClasses() .InheritedFrom<IModule>() .BindAllInterfaces()); foreach (var module in kernel.GetAll<IModule>()) { string name = module.GetModuleMetadata().Name; if (mModules.ContainsKey(name)) { throw new ArgumentException("Module with the name '{0}' already exists!", name); } mModules.Add(name, module); } }
static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); var kernel = new StandardKernel(); kernel.Bind<ISinTrawler>().To<TextsFromLastNightSinTrawler>(); kernel.Bind<IWebPageDownloader>().To<WebPageDownloader>(); kernel.Bind<IIndulgeMeService>().To<NHibernateIndulgeMeService>(); _trawlers = kernel.GetAll<ISinTrawler>(); _indulgeMeService = kernel.Get<IIndulgeMeService>(); foreach (var trawler in _trawlers) { log.DebugFormat("Trawling sins from {0}...", trawler.SourceName); var sins = trawler.GetSins(); log.DebugFormat("Persisting {0} sins...", sins.Sins.Count()); _indulgeMeService.SaveSins(sins.Sins); log.Debug("Done"); } }
public MainGame() { //var input = new InputManager(Services, Window.Handle); IKernel kernel = new StandardKernel(); kernel.Load(Assembly.GetExecutingAssembly()); var elementList = kernel.GetAll<IRoverElement>(); _controllerService = kernel.Get<IControllerService>(); _controllerService.Init(Services, Window.Handle); Components.Add(_controllerService.InputManager); _roverElementList = elementList.ToList(); _graphics = new GraphicsDeviceManager(this); //_mjpegService = kernel.Get<IMjpegService>(); //_networkService = kernel.Get<INetworkService>(); //List<INetworkListener> networkListenerList = kernel.Get<List<INetworkListener>>(); //_networkService.NetworkListenerList = networkListenerList; //_batteryControlService = kernel.Get<IBatteryControlService>(); //_headlightService = kernel.Get<IHeadlightService>();// new HeadlightService(_networkService); Content.RootDirectory = "Content"; }
static void Main(string[] args) { IKernel kernel = new StandardKernel(new OrmConfigurationModule(), new HarnessModule()); kernel.Rebind<ISampleSizeStep>().To<PlusOneSampleSizeStep>(); var config = kernel.Get<IRunnerConfig>(); List<ScenarioInRunResult> allRunResults = new List<ScenarioInRunResult>(); for (int i = 0; i < config.NumberOfRuns; i++) { Console.WriteLine(String.Format("Starting run number {0} at {1}", i, DateTime.Now.ToShortTimeString())); allRunResults.AddRange(kernel.Get<ScenarioRunner>().Run(config.MaximumSampleSize, new CancellationToken()) .Select(r => new ScenarioInRunResult { ApplicationTime = r.ApplicationTime, CommitTime = r.CommitTime, ConfigurationName = r.ConfigurationName, MemoryUsage = r.MemoryUsage, SampleSize = r.SampleSize, ScenarioName = r.ScenarioName, SetupTime = r.SetupTime, Status = r.Status, Technology = r.Technology, RunNumber = i + 1 })); } foreach (var formatter in kernel.GetAll<IResultFormatter<ScenarioInRunResult>>()) { formatter.FormatResults(allRunResults); } Console.ReadLine(); }
public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState routingState = null) { #region Handle Optional Parameters Router = routingState ?? new RoutingState(); var kernel = new StandardKernel(); RxApp.DependencyResolver = dependencyResolver ?? new FuncDependencyResolver((type, contract) => kernel.GetAll(type, contract)); if (dependencyResolver == null) RxApp.InitializeCustomResolver((obj, type) => kernel.Bind(type).ToConstant(obj)); #endregion #region Ninject Setup // Singletons kernel.Bind<IScreen>().ToConstant<AppBootstrapper>(this); kernel.Bind<ILogPeopleIn>().To<LoginManager>().InSingletonScope(); // View resolution kernel.Bind<IViewFor<LoginWidgetViewModel>>().To<LoginWidgetView>(); kernel.Bind<IViewFor<MainViewModel>>().To<MainView>(); kernel.Bind<IViewFor<CreateTicketsViewModel>>().To<CreateTicketsView>(); kernel.Bind<IViewFor<DispatchViewModel>>().To<DispatchView>(); kernel.Bind<IViewFor<AssignedTicketsViewModel>>().To<AssignedTicketsView>(); // Persistence kernel.Bind<ISession>().To<TicketingSession>().InParentScope(); #endregion LogHost.Default.Level = LogLevel.Debug; LoginWidgetViewModel = kernel.Get<LoginWidgetViewModel>(); Router.Navigate.Execute(kernel.Get<MainViewModel>()); }
/// <summary> /// Compiles the built-in embedded resources. /// </summary> private static void BuiltinCompile() { // Create kernel. var kernel = new StandardKernel(); kernel.Load<ProtogameAssetIoCModule>(); kernel.Load<ProtogameScriptIoCModule>(); var services = new GameServiceContainer(); var assetContentManager = new AssetContentManager(services); kernel.Bind<IAssetContentManager>().ToMethod(x => assetContentManager); // Only allow source and raw load strategies. kernel.Unbind<ILoadStrategy>(); kernel.Bind<ILoadStrategy>().To<LocalSourceLoadStrategy>(); var assetModule = new ProtogameAssetIoCModule(); assetModule.LoadRawAssetStrategies(kernel); // Set up remaining bindings. kernel.Bind<IAssetCleanup>().To<DefaultAssetCleanup>(); kernel.Bind<IAssetOutOfDateCalculator>().To<DefaultAssetOutOfDateCalculator>(); kernel.Bind<IAssetCompilationEngine>().To<DefaultAssetCompilationEngine>(); // Rebind for builtin compilation. kernel.Rebind<IRawAssetLoader>().To<BuiltinRawAssetLoader>(); // Set up the compiled asset saver. var compiledAssetSaver = new CompiledAssetSaver(); // Retrieve the asset manager. var assetManager = kernel.Get<LocalAssetManager>(); assetManager.AllowSourceOnly = true; assetManager.SkipCompilation = true; // Retrieve the transparent asset compiler. var assetCompiler = kernel.Get<ITransparentAssetCompiler>(); // Retrieve all of the asset savers. var savers = kernel.GetAll<IAssetSaver>(); var rawLoader = kernel.Get<IRawAssetLoader>(); // For each of the platforms, perform the compilation of assets. foreach (var platformName in new[] { "Android", "iOS", "Linux", "MacOSX", "Ouya", "RaspberryPi", "Windows", "WindowsPhone8", "WindowsStoreApp" }) { Console.WriteLine("Starting compilation for " + platformName); var platform = (TargetPlatform)Enum.Parse(typeof(TargetPlatform), platformName); var outputPath = Environment.CurrentDirectory; assetManager.RescanAssets(); // Create the output directory if it doesn't exist. if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } // Get a list of asset names that we need to recompile for this platform. var assetNames = rawLoader.ScanRawAssets(); foreach (var asset in assetNames.Select(assetManager.GetUnresolved)) { assetCompiler.HandlePlatform(asset, platform, true); foreach (var saver in savers) { var canSave = false; try { canSave = saver.CanHandle(asset); } catch (Exception) { } if (canSave) { try { var result = saver.Handle(asset, AssetTarget.CompiledFile); compiledAssetSaver.SaveCompiledAsset( outputPath, asset.Name, result, result is CompiledAsset, platformName); Console.WriteLine("Compiled " + asset.Name + " for " + platform); break; } catch (Exception ex) { Console.WriteLine("ERROR: Unable to compile " + asset.Name + " for " + platform); Console.WriteLine("ERROR: " + ex.GetType().FullName + ": " + ex.Message); break; } } } assetManager.Dirty(asset.Name); } } }
public void CanRegisterMultipleDispensers() { IKernel kernel = new StandardKernel(new MultipleDispenserModule()); IEnumerable<IJellybeanDispenser> dispensers = kernel.GetAll<IJellybeanDispenser>(); Assert.IsNotNull(dispensers); Assert.AreEqual(2, dispensers.Count()); }
static void Main(string[] args) { IKernel kernel = new StandardKernel(); // Example 1 - simple 1 to 1 binding kernel.Bind<IAnimal>().To<Monkey>(); var animal = kernel.Get<IAnimal>(); Console.WriteLine("object is of type {0}", animal.GetType()); kernel.Unbind<IAnimal>(); // Example 2 - simple 1 to 1 binding kernel.Bind<IAnimal>().To<Tiger>(); var animal2 = kernel.Get<IAnimal>(); Console.WriteLine("object is of type {0}", animal2.GetType()); kernel.Unbind<IAnimal>(); // Example 3 - one to many binding string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); kernel.Bind( c => c.FromAssembliesInPath(path).SelectAllClasses().InheritedFrom<IAnimal>().BindAllInterfaces()); kernel.GetAll<IAnimal>().ToList().ForEach( a => Console.WriteLine("{0} implements IAnimal",a.GetType())); kernel.Unbind<IAnimal>(); // Example 4 - inject dependencies into constructor kernel.Bind<IAnimal>().To<Monkey>(); kernel.Bind<ICar>().To<Volvo>(); kernel.Bind( c => c.FromAssembliesInPath(path).SelectAllClasses().InheritedFrom<IServiceA>().BindAllInterfaces()); var serviceA = kernel.Get<IServiceA>(); Console.WriteLine("Service is of type {0} and has an animal of type {1} and a car of type {2}",serviceA.GetType(),serviceA.Animal,serviceA.Car); kernel.Unbind<IAnimal>(); kernel.Unbind<ICar>(); kernel.Unbind<IServiceA>(); // Example 5 - new object versus singleton kernel.Bind<IAnimal>().To<Tiger>(); var tiger1 = kernel.Get<IAnimal>(); var tiger2 = kernel.Get<IAnimal>(); if (tiger1 == tiger2) Console.WriteLine("tiger1 is the same object as tiger2"); else Console.WriteLine("tiger1 is NOT the same object as tiger2"); kernel.Unbind<IAnimal>(); kernel.Bind<IAnimal>().To<Monkey>().InSingletonScope(); tiger1 = kernel.Get<IAnimal>(); tiger2 = kernel.Get<IAnimal>(); if (tiger1 == tiger2) Console.WriteLine("tiger1 is the same object as tiger2"); else Console.WriteLine("tiger1 is NOT the same object as tiger2"); kernel.Unbind<IAnimal>(); // Example 6 - bind to an class that implements two interfaces kernel.Bind<IServiceB, IServiceC>().To<ServiceBC>().InSingletonScope(); var serviceB_impl = kernel.Get<IServiceB>(); var serviceC_impl = kernel.Get<IServiceC>(); Console.ReadKey(); }
public static void Main(string[] args) { var kernel = new StandardKernel(); kernel.Load<CSharpLibraryNinjectModule>(); string settings = null; string root = null; bool version = false; bool help = false; var options = new OptionSet { { "s|settings=", v => settings = v }, { "settings-base64=", v => settings = Encoding.ASCII.GetString(Convert.FromBase64String(v)) }, { "r|root=", v => root = v }, { "h|help", v => help = true }, { "v|version", v => version = true } }; List<string> files; try { files = options.Parse(args); } catch (OptionException e) { Console.Write("cslint: "); Console.WriteLine(e.Message); Console.WriteLine("Try `cslint --help' for more information."); return; } if (version) { Console.WriteLine("1"); return; } if (help) { ShowHelp(options); return; } if (files.Count == 0) { Console.Write("cslint: "); Console.WriteLine("You must supply at least one file to lint."); Console.WriteLine("Try `cslint --help' for more information."); return; } if (!files.All(File.Exists)) { Console.Write("cslint: "); Console.WriteLine("Unable to locate one or more files specified."); Console.WriteLine("Try `cslint --help' for more information."); return; } var settingsJson = new JsonSettings(settings); kernel.Bind<ISettings>().ToMethod(x => settingsJson); var allResults = new List<LintResults>(); foreach (var file in files) { var results = new LintResults(); results.FileName = new FileInfo(file).FullName; results.BaseName = new FileInfo(file).Name; if (root != null && Directory.Exists(root)) Directory.SetCurrentDirectory(root); if (results.FileName.StartsWith(Environment.CurrentDirectory)) results.FileName = results.FileName.Substring(Environment.CurrentDirectory.Length + 1); var linters = kernel.GetAll<ILinter>(); foreach (var linter in linters) linter.Process(results); allResults.Add(results); } Console.Write(JsonConvert.SerializeObject(allResults)); }