Пример #1
1
        /// <summary>
        /// Configures the DI container
        /// </summary>
        /// <returns>configured kernel</returns>
        static IKernel Configure()
        {
            var kernel = new StandardKernel();

			//TODO: Move this to a module
			kernel.Bind<IClock> ().To<LinuxSystemClock> ().InSingletonScope ();

            //infrastructure modules
			kernel.Load(new List<NinjectModule>()
            {
				new LoggingModule(new List<string>(){"Log.config"})
            });

			var logger = kernel.Get<ILogger> ();

			logger.Info ("Loading Plugins...");
			//plugins
			kernel.Load (new string[] { "*.Plugin.dll" });

			logger.Info ("Loading Core...");
			//core services/controllers
            kernel.Bind<IRaceController>().To<RaceController>()
                .InSingletonScope()
                .WithConstructorArgument("autoRoundMarkDistanceMeters", AppConfig.AutoRoundMarkDistanceMeters);
			kernel.Bind<Supervisor>().ToSelf()
                .InSingletonScope()
                .WithConstructorArgument("cycleTime", AppConfig.TargetCycleTime);
                
            return kernel;
        }
Пример #2
0
        static void Main(string[] args)
        {
            var publisher = new Publisher();

            //Utan Ninject och med dependencies
            var websiteWithDependencies = new WebSiteWithDependencies {MainHeader = "Utan Ninject och med dependencies"};
            publisher.Render(websiteWithDependencies);

            //Utan Ninject fast med konstruktorer
            var dataBase = new OracleDatabase("connectionstring:123.456.789");
            var articleRepository = new ArticleRepository(dataBase);
            var webSite = new WebSite(articleRepository) {MainHeader = "Utan Ninject fast med konstruktorer"};
            publisher.Render(webSite);

            //Med Ninject
            var kernel = new StandardKernel();
            kernel.Bind<IDatabase>().ToMethod(m => new OracleDatabase("connectionstring:123.456.789"));
            kernel.Bind<IArticleRepository>().To<ArticleRepository>();

            var ninjectWebsite = kernel.Get<WebSite>();
            ninjectWebsite.MainHeader = "Med Ninject";
            publisher.Render(ninjectWebsite);

            Console.Read();
        }
Пример #3
0
 static Injector()
 {
     Container = new StandardKernel();
     Container.Load(System.Reflection.Assembly.GetCallingAssembly());
     Container.Bind(x => x.FromThisAssembly().SelectAllClasses().BindDefaultInterface());
     Container.Bind(x => x.FromThisAssembly().SelectAllClasses().BindAllInterfaces());
 }
Пример #4
0
 private StandardKernel GetKernel()
 {
     var kernel = new StandardKernel();
     kernel.Bind<ISecurityProvider>().To<FakeSecurityProvider>();
     kernel.Bind<ISourceProvider>().To<FakeSourceProvider>();
     return kernel;
 }
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var documentStore = new EmbeddableDocumentStore
                {
                    UseEmbeddedHttpServer = true,
                    DataDirectory = "App_Data",
                    Configuration =
                        {
                            Port = 12345,
                        },
                    Conventions =
                        {
                            CustomizeJsonSerializer = MvcApplication.SetupSerializer
                        }
                };
            documentStore.Initialize();
            var manager = new SubscriptionManager(documentStore);

            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            kernel.Bind<IDocumentStore>()
                  .ToMethod(context => documentStore)
                  .InSingletonScope();
            RegisterServices(kernel);
            kernel.Bind<SubscriptionManager>().ToMethod(context => manager).InSingletonScope();
            return kernel;
        }
Пример #6
0
        static void Main()
        {
            StandardKernel kernel = new StandardKernel();

            kernel.Bind<IValueCalculator>().To<LinqValueCalculator>();

            // Property

            //kernel.Bind<IDiscountHelper>().To<DefaultDiscountHelper>().WithPropertyValue("DiscountSize", 50m);

            // Constructor argument

            kernel.Bind<IDiscountHelper>().To<DefaultDiscountHelper>().WithConstructorArgument("discountRate", 50M);

            IValueCalculator valueCalc = kernel.Get<IValueCalculator>();

            ShoppingCart cart = new ShoppingCart(valueCalc);

            Console.WriteLine("Total is: {0}", cart.CalculateStockValue());

            // Self-binding

            // this:

            IValueCalculator calc2 = kernel.Get<IValueCalculator>();
            ShoppingCart cart2 = new ShoppingCart(calc2);

            // is equivalent to:

            ShoppingCart cart3 = kernel.Get<ShoppingCart>();

            //kernel.Bind<ShoppingCart>().ToSelf().WithParameter("<parameterName>", <paramvalue>);
        }
Пример #7
0
        public ViewModelLocator()
        {
            var kernel = new StandardKernel();
            kernel.Bind<IKeyboardService>().To<DefaultKeyboardService>();

            if (ViewModelBase.IsInDesignModeStatic)
            {
                kernel.Bind<IConfigurationService>().To<DesignConfigurationService>();
                kernel.Bind<INuiService>().To<MockNuiService>();
            }
            else
            {
                kernel.Bind<IConfigurationService>().To<AppConfigConfigurationService>();
                kernel.Bind<INuiService>().To<KinectNuiService>();
            }

            nuiService = kernel.Get<INuiService>();

            main = new MainViewModel(
                kernel.Get<IConfigurationService>(),
                nuiService,
                kernel.Get<IKeyboardService>());

            boundingBox = new BoundingBoxViewModel(
                nuiService);

            explorer = new ExplorerViewModel(
                nuiService, kernel.Get<IConfigurationService>());

            math = new MathViewModel();
        }
Пример #8
0
        static void Main(string[] args)
        {
            StandardKernel kernel = new StandardKernel();
            kernel.Bind<IWeapon>().To<Sword>();
            var samurai = kernel.Get<Samurai>();

            samurai.Attack("the evildoers");

            kernel.Bind<IItem>().To<Ration>();
            var samurai2 = kernel.Get<Samurai>();

            StandardKernel kernel2 = new StandardKernel();
            kernel2.Bind<IWeapon>().To<Shuriken>();
            kernel2.Bind<IItem>().To<Ration>();
            var ninja = kernel2.Get<Ninja>();

            StandardKernel kernel3 = new StandardKernel();
            kernel3.Bind<IWeapon>().To<Shuriken>();
            kernel3.Bind<IItem>().To<Ration>();
            kernel3.Bind<IItem>().To<Ration>();
            var ninja2 = kernel3.Get<Ninja>();

            StandardKernel kernel4 = new StandardKernel(new NinjaModule());
            var ninja3 = kernel4.Get<Ninja>();

            Console.ReadLine();
        }
        public void ConstructorArguments_Void_ValueTypeParameters_NoInterceptor()
        {
            const int DependencyNumber = 5;

            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind<IDynamicInterceptorManager>().To<DynamicInterceptorManager>();
                kernel.Bind<IDynamicInterceptorCollection>().ToConstant(new FakeDynamicInterceptorCollection());
                kernel.Bind<IDependency>().To<Dependency>()
                    .WithConstructorArgument("number", DependencyNumber);

                var instance = kernel.Get<IntegrationWithConstructorArgument>();

                instance.AssertInternalNumberIs(0);

                instance.InitializeInternalNumberFromDependency();
                instance.AssertInternalNumberIs(5);

                instance.MultiplyInternalNumberByThree();
                instance.AssertInternalNumberIs(15);

                instance.MultiplyInternalNumber(4);
                instance.AssertInternalNumberIs(60);
            }
        }
Пример #10
0
 private static void RegisterServices(StandardKernel kernel)
 {
     kernel.Bind<IUnitOfWorkService>().To<UnitOfWorkService>();
     kernel.Bind<ICategoriaAppService>().To<CategoriaAppService>();
     kernel.Bind<IContatoAppService>().To<ContatoAppService>();
     kernel.Bind<IUsuarioAppService>().To<UsuarioAppService>();
 }
Пример #11
0
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            // Fetch application settings and instantiate a DoctrineShipsSettings object.
            DoctrineShipsSettings doctrineShipsSettings = new DoctrineShipsSettings(
                WebConfigurationManager.AppSettings["TaskKey"],
                WebConfigurationManager.AppSettings["SecondKey"],
                WebConfigurationManager.AppSettings["WebsiteDomain"],
                Conversion.StringToInt32(WebConfigurationManager.AppSettings["CorpApiId"]),
                WebConfigurationManager.AppSettings["CorpApiKey"],
                WebConfigurationManager.AppSettings["TwitterConsumerKey"],
                WebConfigurationManager.AppSettings["TwitterConsumerSecret"],
                WebConfigurationManager.AppSettings["TwitterAccessToken"],
                WebConfigurationManager.AppSettings["TwitterAccessTokenSecret"],
                WebConfigurationManager.AppSettings["Brand"]
            );

            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            kernel.Bind<IDoctrineShipsServices>().To<DoctrineShipsServices>();
            kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
            kernel.Bind<IEveDataSource>().To<EveDataSourceCached>();
            kernel.Bind<IDbContext>().To<DoctrineShipsContext>();
            kernel.Bind<IDoctrineShipsRepository>().To<DoctrineShipsRepository>();
            kernel.Bind<IDoctrineShipsValidation>().To<DoctrineShipsValidation>();
            kernel.Bind<ISystemLogger>().To<SystemLogger>();
            kernel.Bind<ISystemLoggerStore>().To<DoctrineShipsRepository>();
            kernel.Bind<IDoctrineShipsSettings>().ToConstant(doctrineShipsSettings);

            RegisterServices(kernel);
            return kernel;
        }
Пример #12
0
 /// <summary>
 /// Creates the kernel that will manage your application.
 /// </summary>
 /// <returns>The created kernel.</returns>
 protected override IKernel CreateKernel()
 {
     var kernel = new StandardKernel();
     kernel.Bind<IHomeControllerModel>().To<HomeControllerModel>();
     kernel.Bind<ILog>().ToMethod(ctx => LogManager.GetLogger("xxx"));
     return kernel;
 }
        public void ParsesCruiseControlServerCorrectly()
        {
            var kernel = new StandardKernel();

            var parser = kernel.Get<CruiseControlConfigParser>();

            kernel.Bind<ITimer>().ToConstant(new Mock<ITimer>().Object);
            kernel.Bind<IParser>().ToConstant(new Mock<IParser>().Object).Named("CruiseControl");

            var config = new YamlMappingNode
                             {
                                 {"url", "http://goserver.localdomain:8153/go/cctray.xml"},
                                 {"username", "ci"},
                                 {"password", "secret"}
                             };
            var pipeline1 = new YamlMappingNode {{"name", "Cosby-Kid"}};
            var pipeline2 = new YamlMappingNode { { "name", "Family-Tieman" } };
            var pipelines = new YamlSequenceNode {pipeline1, pipeline2};
            config.Add("pipelines",pipelines);

            var cruiseControlServer = parser.Parse(config) as CruiseControlServer;
            Assert.IsNotNull(cruiseControlServer);
            Assert.IsNotNull(cruiseControlServer.Config);
            var cruiseControlServerconfig = cruiseControlServer.Config;
            Assert.AreEqual("http://goserver.localdomain:8153/go/cctray.xml", cruiseControlServerconfig.URL);
            Assert.AreEqual("ci", cruiseControlServerconfig.Username);
            Assert.AreEqual("secret", cruiseControlServerconfig.Password);
            Assert.IsNotNull(cruiseControlServerconfig.Pipelines);
            Assert.AreEqual(2, cruiseControlServerconfig.Pipelines.Count());
        }
        static void Main(string[] args)
        {           
            IKernel kernel = new StandardKernel();
            kernel.Bind<IBookRepository>().To<XmlFileRepository>().WithConstructorArgument(@"../../books.xml");
            kernel.Bind<ILogger>().To<Logger>();            
            kernel.Bind<IXmlExporter>().To<LinqToXmlExporter>();
            kernel.Bind<IBookListService>().To<BookListService>();
            IBookList list = kernel.Get<BookList>();

            Console.WriteLine("list.Export ended correctly? : " + list.Export(@"../../exported.xml")); 

            IKernel kernelForFilteredList = new StandardKernel();
            kernelForFilteredList.Bind<IBookRepository>().To<BinaryFileRepository>().WithConstructorArgument(@"../../filteredbooks.txt");
            kernelForFilteredList.Bind<ILogger>().To<Logger>();
            kernelForFilteredList.Bind<IXmlExporter>().To<XmlWriterExporter>();
            kernelForFilteredList.Bind<IBookListService>().To<BookListService>();
            IBookList filteredList = kernelForFilteredList.Get<BookList>();

            Console.WriteLine("list.Filter ended correctly? : " + list.Filter((Book b) =>
            {
                if (b.Edition == 1)
                    return true;
                else 
                    return false;
            },
            filteredList));

            Console.WriteLine("filteredlist.Export ended correctly? : " + filteredList.Export(@"../../filteredexported.xml"));
            Console.WriteLine();

            // Uncomment this procedure to check, that all methods from Day7 works correctly
            //DoSomeStuffToEnsureThatAllWorks(list); 

            Console.ReadLine();
        }
Пример #15
0
        static void Main(string[] args)
        {
            var uploadManager = new UploadManager();
            //uploadManager.UploadRestaurantData();


            
            IKernel kernal = new StandardKernel();
            kernal.Load(Assembly.GetExecutingAssembly());

            kernal.Bind(typeof(IRepository<>)).To(typeof(Repository<>));

            kernal.Bind<IUserService>().To<UserService>();
            kernal.Bind<IRestaurantService>().To<RestaurantService>();



            kernal.Bind<IService>().To<ServiceClass>();
            var service = kernal.Get<ServiceBase>();
            service.ImplementServiceMember();


            var restoService = kernal.Get<RestaurantServiceBase>();
            restoService.GetItems();
            

            Console.ReadLine();

        }
Пример #16
0
        public void ConstructorArguments_Void_ValueTypeParameters_InterceptorReplacingArgument()
        {
            const int DependencyNumber = 5;
            var fakeInterceptor = new Mock<IDynamicInterceptor>();
            fakeInterceptor
                .Setup(x => x.Intercept(It.IsAny<IInvocation>()))
                .Callback<IInvocation>(
                    invocation =>
                        {
                            if (invocation.Method.Name == "MultiplyInternalNumber")
                            {
                                invocation.Arguments[0] = 8;
                            }

                            invocation.Proceed(); 
                        });

            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind<IDynamicInterceptorManager>().To<DynamicInterceptorManager>();
                kernel.Bind<IDependency>().To<Dependency>()
                    .WithConstructorArgument("number", DependencyNumber);
                kernel.Bind<IDynamicInterceptorCollection>()
                    .ToConstant(new FakeDynamicInterceptorCollection(fakeInterceptor.Object));

                var instance = kernel.Get<IntegrationWithConstructorArgument>();

                instance.InitializeInternalNumberFromDependency();

                // interceptor overrides 3 with 8
                instance.MultiplyInternalNumber(3);
                
                instance.AssertInternalNumberIs(40);
            }
        }
Пример #17
0
        public void Should_not_throw_exception_when_loading_multiple_inline_modules()
        {
            IKernel kernel = new StandardKernel();

            kernel.Bind<IService>().To<ServiceImpl>();
            kernel.Bind<IService2>().To<Service2Impl>();
        }
Пример #18
0
        public Working()
        {
            // 1 create the kernel
            var kernel = new StandardKernel();

            kernel.Bind<ICreditCard>().To<Visa>();
            kernel.Bind<ICreditCard>().To<MasterCard>().InSingletonScope();
            kernel.Bind<Shopper>().ToSelf().InSingletonScope();

            // 5 modules
            kernel.Load(new WorkingModule());

            // 6 xml config
            kernel.Load(Helpers.AssemblyDirectory + "\\*.xml");

            // 7 conventions
            kernel.Bind(x => x
                              .FromAssembliesInPath(Helpers.AssemblyDirectory)
                              .SelectAllClasses()
                              .InheritedFrom<ICreditCard>()
                              .BindDefaultInterfaces()
                              .Configure(b => b.InSingletonScope()
                                               .WithConstructorArgument("name", "BackupCard"))
                              //.ConfigureFor<Shopper>(b => b.InThreadScope())
                        );
        }
Пример #19
0
        public static void Configure(StandardKernel kernel)
        {
            kernel.Bind(x => x.FromAssembliesMatching("Alejandria.*")
                                 .SelectAllClasses()
                                 .BindAllInterfaces()
                                 .Configure(c => c.InTransientScope()));

            kernel.Bind(x => x.FromAssembliesMatching("Framework.*")
                                 .SelectAllClasses()
                                 .BindAllInterfaces()
                                 .Configure(c => c.InTransientScope()));

            kernel.Bind(x => x.FromAssembliesMatching("Alejandria.*")
                                 .SelectAllInterfaces()
                                 .EndingWith("Factory")
                                 .BindToFactory()
                                 .Configure(c => c.InSingletonScope()));

            kernel.Bind(x => x.FromThisAssembly()
                                 .SelectAllInterfaces()
                                 .Including<IRunAfterLogin>()
                                 .BindAllInterfaces()
                                 .Configure(c => c.InSingletonScope()));

            kernel.Bind<IIocContainer>().To<NinjectIocContainer>().InSingletonScope();
            kernel.Rebind<IClock>().To<Clock>().InSingletonScope();
            //kernel.Bind<IMessageBoxDisplayService>().To<MessageBoxDisplayService>().InSingletonScope();
        }
Пример #20
0
		public void SetUp()
		{
			ReferenceManager = Substitute.For<IReferenceManagement>();
			AppraiserUserService = Substitute.For<IAppraiserUserService>();
			AppraisalCompanyService = Substitute.For<IAppraisalCompanyService>();
			ClientCompanyService = Substitute.For<IClientCompaniesListService>();
			ClientBranchesService = Substitute.For<IBranchesService>();
			ClientCompanyProfileService = Substitute.For<IClientCompanyProfileService>();
			Target = new CommonFunctionsController(AppraiserUserService, ClientBranchesService, ReferenceManager, AppraisalCompanyService, ClientCompanyService, ClientCompanyProfileService);

			IKernel kernel = new StandardKernel();
			var refRepository = Substitute.For<IReferenceRepository>();
			refRepository.GetRoles().ReturnsForAnyArgs(new List<Role>
			{
				new Role { DisplayName = "Appraiser", Id = 1 },
				new Role { DisplayName = "Appraisal Company Admin", Id = 2 },
				new Role { DisplayName = "DVS Super Admin", Id = 3 },
				new Role { DisplayName = "DVS Admin", Id = 4 },
				new Role { DisplayName = "Company Admin and Appraiser", Id = 5 }
			});
			refRepository.GetRole(RoleType.AppraisalCompanyAdmin).Returns(new Role { DisplayName = "Appraisal Company Admin", Id = 2 });
			refRepository.GetRole(RoleType.DvsAdmin).Returns(new Role { DisplayName = "DVS Admin", Id = 4 });

			kernel.Bind<IReferenceRepository>().ToConstant(refRepository);
			kernel.Bind<IReferenceManagement>().To<ReferenceManagement>().InSingletonScope();
			kernel.Bind<ICacheService>().To<FakeCacheService>();
			Singletones.NinjectKernel = kernel;
		}
        public void It_should_resolve_binding_which_matches_all_constraints()
        {
            const string Name = "AnyName";

            var kernel = new StandardKernel();

            // matching name
            kernel
                .Bind<IInterfaceReturnType>()
                .To<InterfaceReturnTypeImplementationBar>()
                .Named(Name);

            // matching metadata key
            kernel
                .Bind<IInterfaceReturnType>()
                .To<InterfaceReturnTypeImplementationBar>()
                .WithMetadata(Constants.Foo, "AnyMetadata");

            // matching name & metadata
            var matchingAllConstraintsInstance = new InterfaceReturnTypeImplementationFoo();
            kernel
                .Bind<IInterfaceReturnType>()
                .ToConstant(matchingAllConstraintsInstance)
                .Named(Name)
                .WithMetadata(Constants.Foo, "AnyMetadata");

            kernel.Bind<IFactoryWithMultipleConstraints>().ToFactory();

            kernel
                .Get<IFactoryWithMultipleConstraints>()
                .Create(Name)
                .Should().BeSameAs(matchingAllConstraintsInstance);
        }
Пример #22
0
        static void Main(string[] args)
        {
            try
            {

                // DI
                IKernel _kernal = new StandardKernel();
                _kernal.Bind<INLogger>().To<NLogger>().InSingletonScope();
                _kernal.Bind<IRepo>().To<Repo>().InSingletonScope();
                _kernal.Bind<IOutputHelper>().To<OutputHelper>().InSingletonScope();
                _logger = _kernal.Get<NLogger>();
                _repo = _kernal.Get<Repo>();
                _output = _kernal.Get<OutputHelper>();

                //ValidateRunLengths();
                var duplicates = ValidateIRIAVG();

                var export = new ExcelExport().AddSheet("Duplicates", duplicates.ToArray());
                export.ExportTo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), System.Configuration.ConfigurationManager.AppSettings["excel:exportFileName"].ToString()));
            }
            catch (Exception ex)
            {
                _output.Write(string.Format("Error: {0}", ex.Message), true);
            }
            Console.WriteLine("Done. Press any key to exist.");
            Console.ReadKey();
        }
Пример #23
0
 private static IKernel GetKernel()
 {
     var kernel = new StandardKernel(GetModules().ToArray());
     kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
     kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
     return kernel;
 }
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var settings = new NinjectSettings();
            settings.LoadExtensions = true;
            settings.ExtensionSearchPatterns = settings.ExtensionSearchPatterns
                .Union(new string[] { "EvidencijaClanova.*.dll" }).ToArray();
            var kernel = new StandardKernel(settings);

            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);

                GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Пример #25
0
        public void InjectorTest()
        {
            Mock <ILogger> mockNlog  = new Mock <ILogger>();
            string         password  = "******";
            string         nameFrom  = "Andrey";
            string         emailFrom = "*****@*****.**";
            string         emailTo   = "*****@*****.**";
            string         header    = "Hi!";
            string         message   = "This was a yours message...";
            string         directory = "C:\\TestFolder";
            var            kernel    = new Ninject.StandardKernel();

            kernel.Bind <ISmtpSender>().To <SmtpSender>().Named("SmtpClient")
            .WithConstructorArgument("emailFrom", emailFrom)
            .WithConstructorArgument("password", password)
            .WithConstructorArgument("nameFrom", nameFrom)
            .WithConstructorArgument("emailTo", emailTo)
            .WithConstructorArgument("header", header)
            .WithConstructorArgument("message", message)
            .WithConstructorArgument("logger", mockNlog.Object);
            kernel.Bind <IFileWatcher>().To <FileWatcher.FileWatcher>().Named("FileWatcher").WithConstructorArgument("directory", directory)
            .WithConstructorArgument("smtpSender", kernel.Get <ISmtpSender>()).WithConstructorArgument("logger", mockNlog.Object);
            var fileWatcher = kernel.Get <IFileWatcher>("FileWatcher");

            Assert.NotNull(fileWatcher);
            var smtpSender = kernel.Get <ISmtpSender>("SmtpClient");

            Assert.NotNull(smtpSender);
        }
Пример #26
0
        public static IKernel CreateContainer()
        {
            var container = new StandardKernel();
            container.Bind(x => x.FromAssemblyContaining<Startup>().SelectAllClasses().BindToSelf());
            container.Bind(x => x.FromAssemblyContaining<IFileSystem>().SelectAllClasses().BindAllInterfaces());

            container.Bind(x =>
            {
                x.FromAssemblyContaining<Startup>()
                    .SelectAllClasses()
                    .Excluding<CachingMediaSource>()
                    .BindAllInterfaces();
            });

            container.Rebind<MediaSourceList>()
                .ToMethod(x =>
                {
                    var mediaSources = x.Kernel.GetAll<IMediaSource>();
                    var sources = new MediaSourceList();
                    sources.AddRange(mediaSources.Select(s => x.Kernel.Get<CachingMediaSource>().WithSource(s)));
                    return sources;
                });

            container.Rebind<ServerConfiguration>()
                .ToMethod(x => x.Kernel.Get<ServerConfigurationLoader>().GetConfiguration())
                .InSingletonScope();

            return container;
        }
Пример #27
0
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();

            try
            {
                kernel
                    .Bind<Func<IKernel>>()
                    .ToMethod(ctx => () => new Bootstrapper().Kernel);

                kernel
                    .Bind<IHttpModule>()
                    .To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);

                return kernel;
            }
            catch
            {
                kernel.Dispose();

                throw;
            }
        }
Пример #28
0
 public void SetupDI()
 {
     IKernel kernel = new StandardKernel();
     kernel.Bind<IReportHubService>().To<FakeReportHubService>();
     kernel.Bind<IReportService>().To<FakeReportService>();
     DependencyResolver.SetResolver(new NinjectDI(kernel));
 }
Пример #29
0
        static void Main(string[] args)
        {
            IKernel container = new StandardKernel();
            container.Bind<IBillingProcessor>().To<BillingProcessor>();
            container.Bind<ICustomer>().To<Customer>();
            container.Bind<INotifier>().To<Notifier>();
            container.Bind<ILogger>().To<Logger>();

            Console.WriteLine("NInject DI Container Example");
            Console.WriteLine();

            OrderInfo orderInfo = new OrderInfo()
            {
                CustomerName = "Miguel Castro",
                Email = "*****@*****.**",
                Product = "Laptop",
                Price = 1200,
                CreditCard = "1234567890"
            };

            Console.WriteLine("Production:");
            Console.WriteLine();

            Commerce commerce = container.Get<Commerce>();
            commerce.ProcessOrder(orderInfo);

            Console.WriteLine();
            Console.WriteLine("Press [Enter] to exit...");
            Console.ReadLine();
        }
Пример #30
0
        public static void PreAppStart()
        {
            var kernel = new StandardKernel();

            kernel.Bind<JabbrContext>()
                .To<JabbrContext>()
                .InRequestScope();

            kernel.Bind<IJabbrRepository>()
                .To<PersistedRepository>()
                .InRequestScope();

            kernel.Bind<IChatService>()
                  .To<ChatService>()
                  .InRequestScope();

            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

            // Perform the required migrations
            DoMigrations();

            // Start the sweeper
            var repositoryFactory = new Func<IJabbrRepository>(() => kernel.Get<IJabbrRepository>());
            _timer = new Timer(_ => Sweep(repositoryFactory), null, _sweepInterval, _sweepInterval);

            SetupErrorHandling();

            Signaler.Instance.DefaultTimeout = TimeSpan.FromSeconds(25);
        }
Пример #31
0
		public void SetUp()
		{
			IKernel kernel = new StandardKernel();
			var refRepository = Substitute.For<IReferenceRepository>();
			refRepository.GetRoles().ReturnsForAnyArgs(new List<Role>() {
        new Role() { DisplayName = "Appraiser", Id = 1 },
        new Role() { DisplayName = "Appraisal Company Admin", Id = 2 },
        new Role() { DisplayName = "DVS Super Admin", Id = 3 },
        new Role() { DisplayName = "DVS Admin", Id = 4 },
        new Role() { DisplayName = "Company Admin and Appraiser", Id = 5 }
      });
			refRepository.GetRole(RoleType.AppraisalCompanyAdmin).Returns(new Role() { DisplayName = "Appraisal Company Admin", Id = 2 });
			refRepository.GetRole(RoleType.DvsAdmin).Returns(new Role() { DisplayName = "DVS Admin", Id = 4 });

			kernel.Bind<IReferenceRepository>().ToConstant(refRepository);
			kernel.Bind<IReferenceManagement>().To<ReferenceManagement>().InSingletonScope();
			kernel.Bind<ICacheService>().To<FakeCacheService>();
			Singletones.NinjectKernel = kernel;
			_userManager = Substitute.For<IUsersManagement>();
			_appraiserService = Substitute.For<IAppraiserUserService>();
			_companyService = Substitute.For<IAppraisalCompanyService>();
			_taskManager = Substitute.For<ITaskManager>();
			_testOrderManager = Substitute.For<ITestOrderManager>();
			//_geocodingValidation = new GeocodingZIPValidation(Substitute.For<IGeocodingDataService>());
			//_geocodingValidation.ValidateAddress(new ValidateAddressArg()).ReturnsForAnyArgs(new ValidateAddressResult { IsValid = true });
			_geocodingValidation = new FakeGeocodingZIPValidation();

			_target = new AppraiserUserAddController(_userManager, _appraiserService, _companyService, _taskManager, _testOrderManager, _geocodingValidation);
			_target.SecurityContext = Substitute.For<ISecurityContext>();
			_target.SecurityContext.CurrentUser.Returns(new User() { Id = 1, Roles = new Role[] { new Role() { Id = (int)RoleType.DvsAdmin } } });
		}
Пример #32
0
    static async Task Main()
    {
        Console.Title = "Samples.UnitOfWork";
        var endpointConfiguration = new EndpointConfiguration("Samples.UnitOfWork");

        endpointConfiguration.UsePersistence <LearningPersistence>();
        endpointConfiguration.UseTransport <LearningTransport>();

        Ninject.StandardKernel kernel = new Ninject.StandardKernel();

        kernel.Bind <ITest>().To <Test>().InUnitOfWorkScope();
        kernel.Bind <IMediator>().To <Mediator>().InUnitOfWorkScope();
        kernel.Bind <ServiceFactory>().ToMethod(ctx => t => ctx.ContextPreservingGet(t)).InUnitOfWorkScope();

        kernel.Bind <INotificationHandler <Meow> >().To <MSub>().InUnitOfWorkScope();

        endpointConfiguration.UseContainer <NinjectBuilder>(c =>
        {
            c.ExistingKernel(kernel);
        });

        var recoverability = endpointConfiguration.Recoverability();

        recoverability.Immediate(
            customizations: immediate =>
        {
            immediate.NumberOfRetries(0);
        });
        recoverability.Delayed(
            customizations: delayed =>
        {
            delayed.NumberOfRetries(0);
        });

        #region ComponentRegistration

        endpointConfiguration.RegisterComponents(
            registration: components =>
        {
            components.ConfigureComponent <CustomManageUnitOfWork>(DependencyLifecycle.InstancePerCall);
        });

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        await Runner.Run(endpointInstance)
        .ConfigureAwait(false);

        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Пример #33
0
        public void Sum_neg()
        {
            var kernel = new Ninject.StandardKernel();

            kernel.Bind <ILogger>().As <Logger>();
            kernel.Bind <Lib.Calculator> ().ToSelf();

            var calc = kernel.Get <Lib.Calculator>();

            var actual = calc.Sum(-2, -3);

            Assert.AreEqual(-5, actual);
        }
Пример #34
0
        public override TInquirer NewInquirer <TInquirer>(Ninject.StandardKernel kernel)
        {
            kernel
            .Bind <UngroupedXileInquirer>()
            .ToSelf().InSingletonScope();
            kernel
            .Bind <UngroupedCentralTendecyInquirer>()
            .ToSelf().InSingletonScope();
            kernel
            .Bind <UngroupedDispersionInquirer>()
            .ToSelf().InSingletonScope();

            return(kernel.Get <TInquirer>());
        }
Пример #35
0
        public void TestMethod1()
        {
            var ker = new Ninject.StandardKernel();

            //ker.Bind<II>().To<A>().Named("a");
            //ker.Bind<II>().To<A>().When(x=>x);
            ker.Bind <II>().To <A>().When(x => x.Target.Name == "a");

            ker.Bind <II>().To <B>().When(x => x.Target.Name == "b");

            //ker.Bind<All>().To<All>().WithConstructorArgument("a", new A()).WithConstructorArgument("b", new B());

            var all = ker.Get <All>();

            all.Print();
        }
Пример #36
0
        public void IsCallingMethodInfoErrorLogger2()
        {
            Mock <ISmtpSender> mockSmtpSender = new Mock <ISmtpSender>();
            Mock <ILogger>     mockNlog       = new Mock <ILogger>();
            string             password       = "******";
            string             nameFrom       = "Andrey";
            string             emailFrom      = "*****@*****.**";
            string             emailTo        = "*****@*****.**";
            string             header         = "Hi!";
            string             message        = "This was a yours message...";
            string             directory      = "C:\\MailFolder";
            var kernel = new Ninject.StandardKernel();
            var s      = mockSmtpSender;

            kernel.Bind <IFileWatcher>().To <FileWatcher.FileWatcher>().Named("FileWatcher").WithConstructorArgument("directory", directory)
            .WithConstructorArgument("smtpSender", s.Object).WithConstructorArgument("logger", LogManager.GetCurrentClassLogger());
            new TaskFactory().StartNew(kernel.Get <IFileWatcher>().Run);
            Thread.Sleep(1000);
            if (File.Exists((directory + "\\r.txt")))
            {
                File.Delete((directory + "\\r.txt"));
            }
            using (File.Create(directory + "\\r.txt"))
                Thread.Sleep(1000);
            s.Verify(x => x.SendEmailAsync(It.IsAny <string>()), Times.Exactly(1));
        }
Пример #37
0
        public void IsCallingMethodInfoErrorLogger1()
        {
            Mock <ILogger> mockNlog  = new Mock <ILogger>();
            string         password  = "******";
            string         nameFrom  = "Andrey";
            string         emailFrom = "*****@*****.**";
            string         emailTo   = "*****@*****.**";
            string         header    = "Hi!";
            string         message   = "This was a yours message...";
            var            kernel    = new Ninject.StandardKernel();

            kernel.Bind <ISmtpSender>().To <SmtpSender>().Named("SmtpClient")
            .WithConstructorArgument("emailFrom", emailFrom)
            .WithConstructorArgument("password", password)
            .WithConstructorArgument("nameFrom", nameFrom)
            .WithConstructorArgument("emailTo", emailTo)
            .WithConstructorArgument("header", header)
            .WithConstructorArgument("message", message)
            .WithConstructorArgument("logger", mockNlog.Object);
            kernel.Get <ISmtpSender>().SendEmailAsync("");
            mockNlog.Verify(x => x.Info(It.IsAny <string>()), Times.Exactly(3));
            mockNlog.Verify(x => x.Error(It.IsAny <string>()), Times.Exactly(1));
            kernel.Get <ISmtpSender>().SendEmailAsync("C:\\MailFolder\\d.txt");
            mockNlog.Verify(x => x.Info(It.IsAny <string>()), Times.Exactly(7));
            mockNlog.Verify(x => x.Error(It.IsAny <string>()), Times.Exactly(1));
        }
Пример #38
0
        public void Sample()
        {
            IKernel kernel = new Ninject.StandardKernel();

            kernel.Bind <ILogger>().To <ConsoleLogger>();
            ILogger logger = kernel.Get <ILogger>();
        }
        public TimeSpan[] Run(IServiceFactory factory, int executions)
        {
            IKernel kernel = new Ninject.StandardKernel();

            kernel.Bind <IBasicService>().To <BasicService>();
            kernel.Bind <IMediumComplexityService>().To <MediumComplexityService>().InSingletonScope();
            kernel.Bind <IComplexService>().To <ComplexService>();

            var times = new TimeSpan[3];

            var stp = new Stopwatch();

            stp.Start();

            for (var count = 0; count < executions; count++)
            {
                kernel.Get <IBasicService>();
            }

            stp.Stop();
            times[0] = stp.Elapsed;

            stp.Restart();

            for (var count = 0; count < executions; count++)
            {
                kernel.Get <IMediumComplexityService>();
            }

            stp.Stop();
            times[1] = stp.Elapsed;

            stp.Restart();

            for (var count = 0; count < executions; count++)
            {
                kernel.Get <IComplexService>();
            }

            stp.Stop();
            times[2] = stp.Elapsed;

            return(times);
        }
Пример #40
0
 static void Main(string[] args)
 {
     using (var kernal = new Ninject.StandardKernel())
     {
         kernal.Bind <ILogger>().To <ConsoleLogger>();
         var service     = kernal.Get <SalutationService>();
         var mailService = new MailService();
         service.SayHello();
     }
 }
Пример #41
0
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        public static void Main()
        {
            var config = new JobHostConfiguration();

            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
            }

            Console.WriteLine("Start Currency Update");

            // IoC
            var kernel = new Ninject.StandardKernel();

            kernel.Bind <ICurrencyExchanger>().To <CurrencyExchanger>();
            kernel.Bind <IOrganizationService>().ToConstructor(x => new OrganizationService(x.Inject <string>())).WithConstructorArgument("connectionStringName", "Xrm");
            kernel.Bind <ICrmServiceContext>().To <CrmServiceContext>().WithConstructorArgument("service", kernel.Get <IOrganizationService>());

            Execute(kernel.Get <ICurrencyExchanger>(), kernel.Get <ICrmServiceContext>());
        }
Пример #42
0
        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);
        }
Пример #43
0
        public ClientContext()
        {
            RegistrationFactory = A.Fake <SignalR.Client.Registration.IFactory>();
            A.CallTo(() => RegistrationFactory.For(A <IIdentity> .Ignored, A <IEntity> .Ignored, A <IObserver <IMessage> > .Ignored))
            .ReturnsLazily(
                call =>
            {
                IIdentity identity            = call.GetArgument <IIdentity>(0);
                IEntity entity                = call.GetArgument <IEntity>(1);
                IObserver <IMessage> observer = call.GetArgument <IObserver <IMessage> >(2);

                return(new SignalR.Client.Registration.Instance(identity.AsDto(), entity.AsDto(), observer));
            }
                );

            Kernel = new Ninject.StandardKernel();
            Kernel.Load(new[] { new SignalR.Client.Module() });
            Kernel.Bind <SignalR.Client.Registration.IFactory>().ToConstant(RegistrationFactory).InSingletonScope();
        }
Пример #44
0
        public static void Register(HttpConfiguration config)
        {
            Ninject.IKernel kernel = new Ninject.StandardKernel();
            //允许私有属性注入
            kernel.Settings.InjectNonPublic = true;

            //service binding
            kernel.Bind <IRepositoryFactory>().To <RepositoryFactory>();

            //为ActionFilter注册服务
            var providers       = config.Services.GetFilterProviders().ToList();
            var defaultprovider = providers.Single(i => i is ActionDescriptorFilterProvider);

            config.Services.Remove(typeof(System.Web.Http.Filters.IFilterProvider), defaultprovider);
            config.Services.Add(typeof(System.Web.Http.Filters.IFilterProvider), new WebApiActionFilterProvider(kernel));

            //mvc inject
            DependencyResolver.SetResolver(new MvcDependencyResolver(kernel));
            //webapi inject
            config.DependencyResolver = new WebApiDependencyResolver(kernel);
        }
Пример #45
0
        static void Main(string[] args)
        {
            var kernel = new Ninject.StandardKernel();
            // 加载所有定义在dll中的注册模块
            var files           = "NBlock*.dll,*Models.dll,*Services.dll,";
            var configLoadFiles = ConfigurationManager.AppSettings["RegisterModules"] ?? "";

            kernel.Load((files + configLoadFiles).Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));

            // 注册服务
            kernel.Bind <ILogService>().To <Log4NetService>().InSingletonScope();

            // 设置依赖注入
            ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(kernel));

            // 配置Log服务
            ServiceLocator.Current.GetInstance <ILogService>().Configure();

            // 启动服务
            var host = HostFactory.New(x =>
            {
                x.Service <QuartzService>();
                x.SetDescription(ConfigurationManager.AppSettings["ServiceDescription"]);
                x.SetDisplayName(ConfigurationManager.AppSettings["ServiceDisplayName"]);
                x.SetServiceName(ConfigurationManager.AppSettings["ServiceName"]);
                x.RunAsLocalSystem();
                x.StartAutomatically();
                x.AfterUninstall(() =>
                {
                    // TODO 删除调度器表记录

                    LogManager.GetCurrentClassLogger().Info("服务卸载成功");
                });
            });

            host.Run();

            System.Console.ReadLine();
        }
Пример #46
0
        private static void Main()
        {
            var container = new Ninject.StandardKernel();

//	        container.Bind<MainForm>().To<MainForm>();
            container.Bind <IUiAction>().To <SaveImageAction>();
            container.Bind <IUiAction>().To <DragonFractalAction>();
            container.Bind <IUiAction>().To <KochFractalAction>();
            container.Bind <IUiAction>().To <ImageSettingsAction>();
            container.Bind <IUiAction>().To <PaletteSettingsAction>();
            container.Bind <Palette>().ToSelf().InSingletonScope();
            container.Bind <IImageHolder, PictureBoxImageHolder>().To <PictureBoxImageHolder>().InSingletonScope();
            container.Bind <KochPainter>().ToSelf().InSingletonScope();

            try {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(container.Get <MainForm>());
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Пример #47
0
        private static IKernel BuildKernel(string[] args, IEnumerable <HelpContent> inHelp)
        {
            var kernel = new Ninject.StandardKernel();

            kernel.Bind <ChangePool>().ToMethod(ctx => new ChangePool());
            kernel.Bind <ItemRackPosition>().ToMethod(ctx => {
                return(new ItemRackPosition(
                           ConsoleAppHelper.ListRacksDefault().Select((rack, i) => Tuple.Create(i + 1, rack)).ToArray()
                           ));
            });
            kernel.Bind <IUserCoinMeckRole>().ToMethod(ctx => new CoinMeckRole());
            kernel.Bind <IUserPurchaseRole>().ToMethod(ctx => new ItemRackRole());
            kernel.Bind <PurchaseContext>().ToSelf();
            kernel.Bind <IRunnerRepository>().ToMethod(ctx => new CommandRunnerRepository(inHelp));

            return(kernel);
        }
Пример #48
0
        /// <summary>
        /// Main.
        /// </summary>
        public static void Main()
        {
            var kernel = new Ninject.StandardKernel();
            // 加载所有定义在dll中的注册模块
            var files = "NBlock*.dll,*Models.dll,*Services.dll,";

            kernel.Load((files).Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));

            // 注册服务
            kernel.Bind <ILogService>().To <Log4NetService>().InSingletonScope();

            // 设置依赖注入
            ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(kernel));

            // 配置Log服务
            ServiceLocator.Current.GetInstance <ILogService>().Configure();

            // 启动服务
            Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

            HostFactory.Run(x =>
            {
                x.RunAsLocalSystem();

                x.SetDescription(Configuration.ServiceDescription);
                x.SetDisplayName(Configuration.ServiceDisplayName);
                x.SetServiceName(Configuration.ServiceName);

                x.Service(factory =>
                {
                    QuartzServer server = QuartzServerFactory.CreateServer();
                    server.Initialize();
                    return(server);
                });
            });
        }
Пример #49
0
        static public void Main(string[] args)
        {
            var _benchmark = new Benchmark(() => new Action(() => new Calculator()));

            _benchmark.Add("SimpleInjector", () =>
            {
                var _container = new SimpleInjector.Container();
                _container.Register <ICalculator, Calculator>(SimpleInjector.Lifestyle.Transient);
                return(() => _container.GetInstance <ICalculator>());
            });
            //TODO : change to test new Puresharp DI recast
            _benchmark.Add("Puresharp", () =>
            {
                var _container = new Puresharp.Composition.Container();
                _container.Add <ICalculator>(() => new Calculator(), Puresharp.Composition.Lifetime.Volatile);
                return(() => _container.Enumerable <ICalculator>());
            });
            //TODO : change to test MEF2
            _benchmark.Add("MEF", () =>
            {
                var _container = new System.Composition.Hosting.ContainerConfiguration().WithAssembly(typeof(ICalculator).Assembly).CreateContainer();
                return(() => _container.GetExport <ICalculator>());
            });
            _benchmark.Add("Castle Windsor", () =>
            {
                var _container = new WindsorContainer();
                _container.Register(Castle.MicroKernel.Registration.Component.For <ICalculator>().ImplementedBy <Calculator>());
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("Unity", () =>
            {
                var _container = new UnityContainer();
                _container.RegisterType <ICalculator, Calculator>();
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("StuctureMap", () =>
            {
                var _container = new StructureMap.Container(_Builder => _Builder.For <ICalculator>().Use <Calculator>());
                return(() => _container.GetInstance <ICalculator>());
            });
            _benchmark.Add("DryIoc", () =>
            {
                var _container = new DryIoc.Container();
                _container.Register <ICalculator, Calculator>();
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("Autofac", () =>
            {
                var _builder = new Autofac.ContainerBuilder();
                _builder.RegisterType <Calculator>().As <ICalculator>();
                var _container = _builder.Build(Autofac.Builder.ContainerBuildOptions.None);
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("Ninject", () =>
            {
                var _container = new Ninject.StandardKernel();
                _container.Bind <ICalculator>().To <Calculator>();
                return(() => _container.Get <ICalculator>());
            });
            _benchmark.Add("Abioc", () =>
            {
                var _setup = new Abioc.Registration.RegistrationSetup();
                _setup.Register <ICalculator, Calculator>();
                var _container = Abioc.ContainerConstruction.Construct(_setup, typeof(ICalculator).Assembly);
                return(() => _container.GetService <ICalculator>());
            });
            _benchmark.Add("Grace", () =>
            {
                var _container = new Grace.DependencyInjection.DependencyInjectionContainer();
                _container.Configure(c => c.Export <Calculator>().As <ICalculator>());
                return(() => _container.Locate <ICalculator>());
            });
            _benchmark.Run(Console.WriteLine);
        }
Пример #50
0
        static void Main(string[] args)
        {
            try
            {
                var profile = new object();
                var test    = new string[] {
                    $"B12B...3.4.5...",
                    $"B6B..T..T",
                    $"..3.",
                    $"...",
                    $"..3.",
                    $"...",
                    $"...T..T",
                };

                var context = new CommandContext();
                var kernel  = new Ninject.StandardKernel();
                kernel.Bind <CommandContext>().ToConstant(context);

                var mainCommandQueue      = new List <string>();
                var teardownCommandQueue  = new List <string>();
                var teardownCommandQueues = new List <List <String> >();
                //var test = kernel.GetAll<CommandTree>();

                var buildup  = true;
                var teardown = false;
                //foreach (var t in test.Split(","))
                //{
                //    switch (t)
                //    {
                //        case "B":
                //            buildup = false;
                //            teardown = true;
                //            break;
                //        case "T":
                //            teardown = false;
                //            break;
                //        default:

                //            if (teardown)
                //            {
                //                teardownCommandQueue.Add(t);
                //                break;
                //            }

                //            mainCommandQueue.Add(t);

                //            break;
                //    }
                //}


                var all = GetInstancesOfInterfaceImplementingClasses <ICommand>((x) => (ICommand)kernel.Get(x));

                foreach (var c in all)
                {
                    Console.WriteLine(c.FriendlyName);
                }

                var queue = new Queue <string>();
                queue.Enqueue("startprofiler");
                queue.Enqueue("startselenium");
                queue.Enqueue("load");
                var tearDownStack = new Stack <Queue <string> >();
                var scopeStack    = new Stack <string>();
                var testStack     = new Stack <string>();
                testStack.Count();

                var resultTree = new TreeNode <string>("base");
                //resultTree.AddChild()


                var item = "";
                scopeStack.Push("a");
                Func <int>    level       = () => testStack.Count(); // short hand for how deep we are
                Func <string> currentStep = () => "currentstep";
                while (queue.Any())
                {
                    item = queue.Dequeue();
                    Console.WriteLine(item);

                    switch (item)
                    {
                    case "load":
                        testStack.Push("test2");
                        // create new scope
                        scopeStack.Push("b");
                        queue.Enqueue(currentStep());
                        break;

                    default:
                        // just do it
                        break;
                    }

                    if (queue.Count() == 0 && level() > 0)
                    {
                        testStack.Pop();
                        queue.Enqueue(currentStep());
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine("Press the ANY key to continue...");
            Console.ReadKey();
            //var writeToFileCommand = new WriteToFileCommand(context);
            //var command = (ICommand)writeToFileCommand;

            //var needsInput = writeToFileCommand as INeedsInput;
            //if (needsInput == null || needsInput.Input())
            //{
            //    Console.WriteLine(command.FriendlyName);
            //    command.Go();
            //}


            //   var subMenu = new ConsoleMenu(args, level: 1)
            //.Add("Sub_One", () => SomeAction("Sub_One"))
            //.Add("Sub_Two", () => SomeAction("Sub_Two"))
            //.Add("Sub_Three", () => SomeAction("Sub_Three"))
            //.Add("Sub_Four", () => SomeAction("Sub_Four"))
            //.Add("Sub_Close", ConsoleMenu.Close)
            //.Configure(config =>
            //{
            //    config.Selector = "--> ";
            //    config.EnableFilter = true;
            //    config.Title = "Submenu";
            //    config.EnableBreadcrumb = true;
            //    config.WriteBreadcrumbAction = titles => Console.WriteLine(string.Join(" / ", titles));
            //});

            //   var menu = new ConsoleMenu(args, level: 0)
            //     .Add("One", () => SomeAction("One"))
            //     .Add("Two", () => SomeAction("Two"))
            //     .Add("Three", () => SomeAction("Three"))
            //     .Add("Sub", subMenu.Show)
            //     .Add("Change me", (thisMenu) => thisMenu.CurrentItem.Name = "I am changed!")
            //     .Add("Close", ConsoleMenu.Close)
            //     .Add("Action then Close", (thisMenu) => { SomeAction("Close"); thisMenu.CloseMenu(); })
            //     .Add("Exit", () => Environment.Exit(0))
            //     .Configure(config =>
            //     {
            //         config.Selector = "--> ";
            //         config.EnableFilter = true;
            //         config.Title = "Main menu";
            //         config.EnableWriteTitle = false;
            //         config.EnableBreadcrumb = true;
            //     });

            //   menu.Show();
        }
Пример #51
0
        public static IKernel init()
        {
            var Kernel = new Ninject.StandardKernel();

            Kernel.Bind <UniqueTicketIdGenerator>().To <DefaultUniqueTicketIdGenerator>();

            Kernel.Bind <AuthenticationViaFormAction>().ToSelf();

            Kernel.Bind <AuthenticationHandler>().To
            <SimpleTestUsernamePasswordAuthenticationHandler>();

            Kernel.Bind <ProxyHandler>().To <Cas20ProxyHandler>();

            Kernel.Bind <ServicesManager>().To <DefaultServicesManagerImpl>();

            Kernel.Bind <AuthenticationManager>().To <AuthenticationManagerImpl>().WithConstructorArgument("authenticationHandlers",
                                                                                                           DeployerConfigContextConfig
                                                                                                           .
                                                                                                           authenticationHandlers)
            .WithConstructorArgument("credentialsToPrincipalResolvers", DeployerConfigContextConfig.credentialsToPrincipalResolvers);


            Kernel.Bind <ServiceRegistryDao>().To <InMemoryServiceRegistryDaoImpl>();

            Kernel.Bind <CentralAuthenticationService>().To <CentralAuthenticationServiceImpl>().WithConstructorArgument(
                "uniqueTicketIdGeneratorsForService", UniqueIdGeneratorsConfig.GetUniqueTicketIdGeneratorsForService())
            .WithConstructorArgument("ticketGrantingTicketExpirationPolicy", TicketExpirationPoliciesConfig.grantingTicketExpirationPolicy)
            .WithConstructorArgument("serviceTicketExpirationPolicy", TicketExpirationPoliciesConfig.serviceTicketExpirationPolicy);

            Kernel.Bind <Credentials>().To <UsernamePasswordCredentials>();

            Kernel.Bind <TicketRegistry>().To <DefaultTicketRegistry>();

            Kernel.Bind <ArgumentExtractor>().To <CasArgumentExtractor>();



            return(Kernel);
            //Kernel.Bind<ExpirationPolicy>().To<NeverExpiresExpirationPolicy>().WhenAnyAnchestorNamed("");
        }