Пример #1
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();
        }
Пример #2
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();

        }
Пример #3
0
 public void ResolveAuto()
 {
     var kernel = new StandardKernel();
     var simpleClass1 = kernel.Get<Simple>();
     var simpleClass2 = kernel.Get<Simple>();
     Assert.AreNotSame(simpleClass1, simpleClass2);
 }
Пример #4
0
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Bind<IDictionaryService>().To<DictionaryService>();
            kernel.Bind<IYammerMessageResponseDeserializer>().To<YammerMessageResponseDeserializer>();
            kernel.Bind<IYammerMessageDatabaseManager>().To<YammerMessageDatabaseManager>();
            kernel.Bind<IYammerMessagePoster>().To<YammerMessagePoster>();
            kernel.Bind<IYammerMessageFetcher>().To<YammerMessageFetcher>();
            kernel.Bind<IYammerMessageServiceManager>().To<YammerMessageServiceManager>();
            kernel.Bind<IYammerTaskRunner>().To<YammerTaskRunner>();
            kernel.Bind<IQuoteRetriever>().To<QuoteRetriever>();
            kernel.Bind<ILoopingTaskRunner>().To<LoopingTaskRunner>();
            kernel.Bind<IEnvironmentInfoProvider>().To<EnvironmentInfoProvider>();
            kernel.Bind<IFileDataProvider>().To<FileDataProvider>();
            kernel.Bind<ISleeper>().To<ThreadSleeper>();
            kernel.Bind<IYammerResponseFetcher>().To<YammerResponseFetcher>();
            kernel.Bind<IYammerCommandFetcher>().To<YammerCommandFetcher>();
            kernel.Bind<IRandomNumberGenerator>().To<RandomNumberGenerator>();
            kernel.Bind<IComplimentFetcher>().To<ComplimentFetcher>();
            kernel.Bind<IComplimentService>().To<ComplimentService>();
            kernel.Bind<IComplimentTextDeserializer>().To<ComplimentTextDeserializer>();
            kernel.Bind<IComplimentTextTransformer>().To<ComplimentTextTransformer>();
            kernel.Bind<IYammerService>().To<YammerService>();
            kernel.Bind<IOauthValueProvider>().To<OauthValueProvider>();

            kernel.Bind<IOauthSessionProvider>().To<OauthSessionProvider>().InSingletonScope();
            kernel.Bind<IYammerDatabase>().To<YammerDatabase>().InSingletonScope();

            var runner = kernel.Get<IYammerTaskRunner>();
            var looper = kernel.Get<ILoopingTaskRunner>();

            looper.AddTask(60000, runner.ExecuteReplies);
        }
Пример #5
0
        static void Main(string[] args)
        {
            Logger.Current.BinaryFileTraceLevel=TraceLevel.Verbose;
            Logger.DefaultBinaryFile.Open();

            IKernel kernel = new StandardKernel(new AutoMapperModule(), new BusinessModule(), new NHibernateModule(), new WCFModule());

            var _serviceManager = kernel.Get<ServiceManager>();

            var _serviceThread = new Thread(_serviceManager.RunServiceManager);

            _serviceThread.Start();

            var _host = new ServiceHost(kernel.Get<ILocationService>(), new Uri("http://localhost:9090/Jimbe"));
            var smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;

            _host.Description.Behaviors.Add(smb);
            _host.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
            _host.AddServiceEndpoint(typeof (ILocationService),
                                     new WSDualHttpBinding(), "");
            _host.Open();

            Console.WriteLine("Host opened");
            Console.ReadLine();
            _serviceManager.RequestStop();
        }
Пример #6
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            var kernel = new StandardKernel(new ServiceModule(), new WindowsTimeServiceModule());           

#if SERVICE
            var ServicesToRun = new System.ServiceProcess.ServiceBase[]
                                {
                                    kernel.Get<WindowsTimeService>()
                                };
            System.ServiceProcess.ServiceBase.Run( ServicesToRun );
#else
            var service = kernel.Get<WindowsTimeService>();
            try
            {
                service.Start(new string[] { });

                do
                {
                } 
                while (Console.ReadLine() != "q");
            }
            finally
            {
                service.Stop();
            }
#endif
        }
Пример #7
0
        static void Main(string[] args)
        {
            //container is called kernal (because it represents the kernal / core of the application

              //var kernal = new StandardKernel();
              //kernal.Bind<ICreditCard>().To<MasterCard>();

              var kernal = new StandardKernel(new MyModule());
              //kernal.Rebind<ICreditCard>().To<MasterCard>();

              //dont have to register all the types.. ninject will automatically register concrete types so we can ask for any concrete type and ninject will know how to create it.. without us having to speciy it specificallly in the container.. makes it a little easier so we don't have to configure every single class that we are going to use.
              //(dont need to register shopper type because its automatic)
              //whenever we ask for an ICreditCard were going to get back a MasterCard.

              var shopper = kernal.Get<Shopper>();
              shopper.Charge();
              Console.WriteLine(shopper.ChargesForCurrentCard);

              kernal.Rebind<ICreditCard>().To<MasterCard>();

              var shopper2 = kernal.Get<Shopper>();
              shopper2.Charge();
              Console.WriteLine(shopper2.ChargesForCurrentCard);

              //Shopper shopper3 = new Shopper();
              //shopper3.Charge();
              //Console.WriteLine(shopper3.ChargesForCurrentCard);

              Console.Read();
        }
        /// <summary>
        /// Award scholarship
        /// </summary>
        public void AwardScholarship()
        {
            // Wrote the resolver myself
            var resolver = new Resolver();

            var rankBy1 = resolver.ChooseRanking("undergrad");
            var award1 = new Award(rankBy1);

            award1.AwardScholarship("100");

            var rankBy2 = resolver.ChooseRanking("grad");
            var award2 = new Award(rankBy2);
            award2.AwardScholarship("200");

            // using Ninject instead of the custom resolver I wrote.
            var kernelContainer = new StandardKernel();
            kernelContainer.Bind<IRanking>().To<RankByGPA>();
            var award3 = kernelContainer.Get<Award>();
            award3.AwardScholarship("101");

            kernelContainer.Rebind<IRanking>().To<RankByInnovation>();
            var award4 = kernelContainer.Get<Award>();
            award4.AwardScholarship("201");

            // using Unity instead of custom resolver.
            var unityContainer = new UnityContainer();
            unityContainer.RegisterType<IRanking, RankByGPA>();
            var award5 = unityContainer.Resolve<Award>();
            award5.AwardScholarship("102");

            unityContainer = new UnityContainer();
            unityContainer.RegisterType<IRanking, RankByInnovation>();
            var award6 = unityContainer.Resolve<Award>();
            award6.AwardScholarship("202");
        }
Пример #9
0
        public void TestPartialParametersInChild()
        {
            var modules = new INinjectModule[]
            {
                new TestModuleChilds(), 
            };

            _kernel = new StandardKernel();
            _kernel.Components.Add<IActivationStrategy, MyMonitorActivationStrategy>();

            _kernel.Load(modules);

            var main1 = _kernel.Get<SomeMainModule>();
            var main2 = _kernel.Get<SomeMainModule>();

            Assert.AreSame(main1, main2);

            var factory = _kernel.Get<IFactory<SomeTimedModule>>();
            SomeTimedModule someTimedModule1 = factory.Create();
            SomeTimedModule someTimedModule2 = factory.Create();

            Assert.AreNotSame(someTimedModule1.InnerModule, someTimedModule2.InnerModule);

            SomeTimedObject someTimedObject = someTimedModule1.ObjFactory.CreateWithParams(1);
            
            
            Assert.AreSame(someTimedObject.ModuleTimed, someTimedModule1.InnerModule);
            Assert.AreSame(someTimedObject.Module, main2);

            SomeTimedObject someTimedObject2 = someTimedModule1.ObjFactory.CreateWithParams(2);
            Assert.AreNotSame(someTimedObject2.TimedObjectInner, someTimedObject.TimedObjectInner);
            Assert.AreSame(someTimedObject2.TimedObjectInner, someTimedObject2.InnerInner.Inner);
        }
Пример #10
0
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Load(new Module());

            var counter = kernel.Get<StatsCounter>();
            var client = kernel.Get<INaiveClient>();
            counter.Stopwatch.Start();
            for (var i = 0; i < TimesToInvoke; i++)
            {
                try
                {
                    client.GetMyDate(DateTime.Today.AddDays(i % 30));
                    counter.TotalSuccess++;
                }
                catch (Exception ex)
                {
                    counter.TotalError++;
                }
            }
            counter.Stopwatch.Stop();

            counter.PrintStats();
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
Пример #11
0
        static void Main(string[] args)
        {
            /*  You should look at the following files to get an idea about what's happening
             *  Program.cs (this file):     Here we configure Log4Net, inject our logger (UXRiskLogger) with Ninject,
             *                              grab the logger so we can use it straigth away and do some basic logging
             *  CustomPatternConverter.cs:  Reads out our custom properties that we define in the UXRiskLogger project
             *  App.config:                 Configures Log4Net and our CustomPatternConverter
             */

            // Read Log4Net config from App.config
            XmlConfigurator.Configure();

            // Inject the logger module with Ninject. This have the benefil that in the other classes you can reach the logger by doing
            // public ILogger Logger { get; set; } inside your class
            // and then log by doing Logger.Info()
            var kernel = new StandardKernel(new Log4NetModule(), new AutomaticLoggingInjectionModule());

            // Since we're doing logging in the application startup, the Injection isn't done yet, and we need to access
            // the logger a bit more manually here.
            var log = kernel.Get<ILoggerFactory>().GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
            var access = kernel.Get<AccessLogger>();

            // Debug log with "Testmessage" as message and "CorID" as Properties["correlationId"]
            log.Debug("Testmessage", Guid.NewGuid().ToString());

            // Info log with "Application started" as message, 43254,32 as Properties["value"] and UnitType.bytes as Properties["unitType"]
            log.Info("Application started", 43254.32, UnitType.bytes);

            // Log from AccessLogger class
            access.DoLog();

            // Wait on keypress to exit.
            Console.ReadLine();
        }
Пример #12
0
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel(new ResolverModule());
            IUserService udb = kernel.Get<IUserService>();
            IRoleService rdb = kernel.Get<IRoleService>();
            IBlogService bdb = kernel.Get<IBlogService>();
            IArticleService adb = kernel.Get<IArticleService>();
            ITagService tdb = kernel.Get<ITagService>();
            var list = udb.GetAll().ToList();
            //var list2 = bdb.GetAll().ToList();
            var list3 = rdb.GetAll().ToList();
            //var list4 = adb.GetAll().ToList();
            var list5 = tdb.GetAll().ToList();
            var role = rdb.GetByName("user");
            //var blog = new DalBlog() { Title = "blog" };
            //var user = new BllUser() { Name = "UserServ", Password = "******", RoleId = role.Id };
            var article = new BllArticle() { Title = "A7", BlogId = 7, Text = "text" };
            var tag = new BllTag() { Name = "SecondTag", };

            //user = udb.GetByName("UserServ");
            //user.Name = "Admin";
            //user.RoleId = rdb.GetByName("admin").Id;
            //udb.Save(user);

            //article = adb.GetById(5);
            //adb.Delete(5);

            var blog = bdb.GetById(7);
            blog.Title = "WAT????";
            bdb.Save(blog);
        }
Пример #13
0
        static void Main(string[] args)
        {
            Ninject.IKernel kernal = new StandardKernel(new Core());
            ////kernal.Bind<IMsgRepo>().To<MsgRepo>();
            _repo = kernal.Get<MsgRepo>();

            _svc = kernal.Get<MsgService>();

            var svcreplies = _svc.GetReplies();
            foreach (var x in svcreplies)
            {
                Console.WriteLine(x.Body);
            }

            Console.WriteLine("enter reply");
            var consoleReply = Console.ReadLine();

            var reply = new Reply()
            {
                Body = consoleReply,
                Created = DateTime.Now,
                TopicId = 1

            };

            _repo.InsertReply(reply);

            var replies = _repo.GetReplies();
            _repo.DeleteReply(replies.First().Id);

            foreach (var x in replies)
            {
                Console.WriteLine(x.Body);
            }

            Main(args);

            //var baseClass = new BaseClass();
            //var derivedOverride = new DerivedOverride();
            //var derivedNew = new DerivedNew();
            //var derivedOverWrite = new DerivedOverwrite();

            //baseClass.Name();
            //derivedOverride.Name();
            //derivedNew.Name();
            //derivedOverWrite.Name();

            //Console.ReadLine();
            //baseClass.Name();
            //derivedOverride.Name();
            //((BaseClass)derivedNew).Name();
            //((BaseClass)derivedOverWrite).Name();
            //Console.ReadLine();

            //var t1 = typeof(BaseClass);
            //Console.WriteLine(t1.Name);
            //Console.WriteLine(t1.Assembly);

            //Console.ReadLine();
        }
Пример #14
0
        private static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            var kernel = new StandardKernel(new PicklesModule());
            var configuration = kernel.Get<Configuration>();

            var commandLineArgumentParser = kernel.Get<CommandLineArgumentParser>();
            var shouldContinue = commandLineArgumentParser.Parse(args, configuration, Console.Out);

            if (shouldContinue)
            {
                if (log.IsInfoEnabled)
                {
                    log.InfoFormat("Pickles v.{0}{1}", Assembly.GetExecutingAssembly().GetName().Version,
                                   Environment.NewLine);
                    log.InfoFormat("Reading features from {0}", configuration.FeatureFolder.FullName);
                }

                var runner = kernel.Get<Runner>();
                runner.Run(kernel);

                if (log.IsInfoEnabled)
                {
                    log.Info("Pickles completed successfully");
                }
            }
        }
Пример #15
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>);
        }
Пример #16
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));
        }
        public static void Main()
        {
            try
            {
                var module = new TriangleModule();
                var kernel = new StandardKernel(module);
                //var context = ZmqContext.Create();
                //var receiver = new MessageReceiver(context);
                //receiver.Listen();
                //var bus = new MessageBus(new MessageSender(context), receiver, new MessageRegistrationList());

                var selectableObjectRepository = kernel.Get<SelectableObjectRepository>();

                //var renderer = kernel.Get<Renderer>();
                //var form = kernel.Get<Form1>();
                //form.GO();
                //renderer.StartRendering();

                var form = kernel.Get<GameFormWpf>();
                form.GO();

                kernel.Dispose();
            }
            catch (OperationCanceledException) { }
        }
Пример #18
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();
        }
Пример #19
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();
        }
Пример #20
0
        /// <summary>Initializes the application.</summary>
        public Global()
        {
            var color = Color.FromHsl(0, 0, 1);

            var escapeAlgorithm = new RenormalizedIterCount();

            var fractalStore = new FractalStore(
                    new Mandelbrot(escapeAlgorithm),
                    new JuliaSet1(escapeAlgorithm),
                    new JuliaSet2(escapeAlgorithm),
                    new JuliaSet3(escapeAlgorithm),
                    new JuliaSet4(escapeAlgorithm)
                );

            var colorizationStore = new ColorizationStore(
                    new BandedColorizer { InnerColor = Colors.Black, Colors = new Color[] { Colors.Blue, Colors.Green, Colors.Yellow } },
                    new ColorInterpolatorColorizer { InnerColor = Colors.Black, Colors = new Color[] { Colors.Chartreuse, Colors.CornflowerBlue, Colors.Red } },
                    new SimpleColorizer()
                );

            var kernel = new StandardKernel(
                    new MainModule(),
                    new StoreModule(fractalStore, colorizationStore)
                );

            var mainWindow = kernel.Get<MainWindow>();
            mainWindow.ViewModel = kernel.Get<MainWindowViewModel>();
            StartupWindow = mainWindow;
        }
Пример #21
0
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel(new Module());
            Configuration.ISettings settings = kernel.Get<Configuration.ISettings>();

            if (settings.Validate())
            {
                kernel.Load(new Io.Spark.Ninject.Module(settings.SparkCore.AccessToken));

                HostFactory.Run(
                    x =>
                    {
                        x.Service<IService>(s =>
                        {
                            s.ConstructUsing(name => kernel.Get<IService>());
                            s.WhenStarted(tc => tc.Start());
                            s.WhenStopped(tc => tc.Stop());
                        });
                        x.RunAsLocalSystem();

                        x.SetDescription("Service for reading values from SparkCore cloud API and writing the values to ElasticSearch");
                        x.SetDisplayName("SparklES");
                        x.SetServiceName("SparklES");
                    }
                );
            };
        }
Пример #22
0
        public static StandardKernel Register( HttpConfiguration config )
        {
            var kernel = new StandardKernel();

            try
            {
                kernel.Bind<IRepository>().ToConstant( new MongoRepository( ConfigurationManager.ConnectionStrings[ "Mongo" ].ConnectionString, "gemfire" ) );
            }
            catch ( Exception ex ) // probably a bad/missing connection string for the mongodb, just use an in-memory store to get running instead
            {
                kernel.Bind<IRepository>().ToConstant( new MemoryRepository() );
            }

            var repo = kernel.Get<IRepository>();

            kernel.Bind<IGameHandler>().ToConstant( new GameHandler( repo ) );
            kernel.Bind<ILoginHandler>().ToConstant( new LoginHandler() );
            kernel.Bind<IRegistrationHandler>().ToConstant( new RegistrationHandler() );
            kernel.Bind<IUserHandler>().ToConstant( new UserHandler( repo ) );
            kernel.Bind<IMappingHandler>().ToConstant( new AutoMapMappingHandler( kernel.Get<IUserHandler>() ) );
            kernel.Bind<IScenarioHandler>().ToConstant( new ScenarioHandler() );

            DependencyResolver.SetResolver( new NinjectMVCDependencyResolver( kernel ) );
            GlobalHost.DependencyResolver = new NinjectSignalRDependencyResolver( kernel );

            return kernel;
        }
Пример #23
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            System.Diagnostics.Debugger.Break();

            var ninjectKernel = new StandardKernel();
            ninjectKernel.Bind<IConfigurationHelper>().To<ConfigurationHelper>();
            if (Environment.UserInteractive)
            {
                ninjectKernel.Bind<ILoggerFactory>().ToConstant<ConsoleLoggerFactory>(new ConsoleLoggerFactory());
            }
            else
            {
                ninjectKernel.Bind<ILoggerFactory>().ToConstant<BasicLoggerFactory>(new BasicLoggerFactory(ninjectKernel.Get<IConfigurationHelper>()));
                //ninjectKernel.Bind<ILoggerFactory>().ToMethod(context => new BasicLoggerFactory()).InSingletonScope(); // Alternative to ToConstant
            }
            var timedService = ninjectKernel.Get<TimedService>();

            if (Environment.UserInteractive)
            {
                timedService.RunFromConsole();
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    timedService
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
Пример #24
0
        public static Bitmap CreateEmbroidery(Bitmap image, int resolutionCoefficient, int cellsCount, Color[] palette, char[] symbols, Color symbolColor, GridType type)
        {
            IKernel kernel = new StandardKernel(new PropertiesModel());

            var patternMapGenerator = kernel.Get<IPatternMapGenerator>();
            var canvasConverter = kernel.Get<ICanvasConverter>();

            var patternCreator = new EmbroideryCreator()
            {
                PatternMapGenerator = patternMapGenerator,
                CanvasConverter = canvasConverter,
            };

            Settings settings = new Settings()
            {
                CellsCount = cellsCount,
                Coefficient = resolutionCoefficient,
                Palette = new Palette(palette),
                Symbols = symbols,
                SymbolColor = symbolColor,
                GridType = type,
                DecoratorsComposition = new DecoratorsComposition()
            };

            if (settings.Palette != null)
                settings.DecoratorsComposition.AddDecorator(new CellsDecorator());
            if (settings.Symbols != null)
                settings.DecoratorsComposition.AddDecorator(new SymbolsDecorator());
            if (settings.GridType != Core.GridType.None)
                settings.DecoratorsComposition.AddDecorator(new GridDecorator());

            Bitmap result = patternCreator.GetEmbroidery(image, settings);

            return result;
        }
Пример #25
0
        static void Main(string[] args)
        {
            IKernel ninjectKernel = new StandardKernel();
            ninjectKernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
            ninjectKernel.Bind<IDiscountHelper>()
                .To<DefaultDiscountHelper>()
                .WithConstructorArgument("sizeParam", 50M);
            //.WithPropertyValue("DiscountSize", 20M);
            IValueCalculator calcImpl = ninjectKernel.Get<IValueCalculator>();

            ShoppingCart cart = new ShoppingCart(calcImpl);
            Console.WriteLine("Total:{0:c} ", cart.CalculateStockValue());

            //Ninject SelfBinding
            ShoppingCart selfBindingCart = ninjectKernel.Get<ShoppingCart>();
            Console.WriteLine("Total:{0:c} ", selfBindingCart.CalculateStockValue());

            //Self binding with parameters
            //ninjectKernel.Bind<ShoppingCart>().ToSelf().WithPropertyValue("", "");

            ninjectKernel.Bind<ShoppingCart>().To<LimitShoppingCart>().WithPropertyValue("ItemLimit", 200M);
            ShoppingCart derivedTypeBindingCart = ninjectKernel.Get<ShoppingCart>();
            Console.WriteLine("Total:{0:c} ", derivedTypeBindingCart.CalculateStockValue());

            //Conditional Binding Methods
            ninjectKernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
            ninjectKernel.Bind<IValueCalculator>()
            .To<IterativeValueCalculator>()
            .WhenInjectedInto<LimitShoppingCart>();

            Console.ReadKey();
        }
Пример #26
0
        static void Main(string[] args)
        {
            Parser.Parse(Config, args);

            Kernel = new StandardKernel();

            Kernel.Load(AppDomain.CurrentDomain.GetAssemblies());

            var repo = Kernel.Get<IRepository>();

            var serial = Kernel.Get<ISerializer>();

            var testResult = Kernel.Get<TestRunResult>();

            if (File.Exists("Config.cfg"))
                Config = serial.ReadFile<BehaviorConfiguration>("Config.cfg");

            repo.DataPath = Config.DataPath;

            var stories = repo.GetItemsWithTaggedChildren(repo.GetAll<Story>(), Config.IncludeTags, Config.ExcludeTags).OrderBy(s => s.Name).ToList();

            stories.ForEach(s => testResult.StoryResults.Add((s as Story).Run(Kernel.Get<ILauncherClient>())));

            testResult.SetResult();

            var testReport = new TestRunReport(testResult);

            testReport.ToFile("TestResults.html");
        }
Пример #27
0
        public ViewModelLocator()
        {
            _container = new StandardKernel();
            _container.Bind<ClockViewModel>().ToSelf().InSingletonScope();
            _container.Bind<FlightsViewModel>().ToSelf().InSingletonScope();
            _container.Bind<AirportsViewModel>().ToSelf().InSingletonScope();
            _container.Bind<IGetAirports>().To<AirportNamesService>().InSingletonScope();
            _container.Bind<IOpenCommunicationChannel>().To<NotificationService>().InSingletonScope();
            _container.Bind<IMonitorFlightsService>().To<MonitoringWebServiceSoapClient>();

            _container.Bind<IGetCurrentLocation>().ToConstant(new PresetLocationService(63.433281, 10.419294));
            _container.Bind<NearestAirportService>().ToConstant(new NearestAirportService(_container.Get<IGetCurrentLocation>()));
            _container.Bind<MonitorServiceClient>().ToConstant(new MonitorServiceClient(_container.Get<IOpenCommunicationChannel>(), _container.Get<IMonitorFlightsService>()));

            if(ViewModelBase.IsInDesignModeStatic)
            {
                _container.Bind<IStoreObjects>().To<DesignTimeObjectStore>().InSingletonScope();
                _container.Bind<IGetFlights>().To<DesignTimeFlightsService>().InSingletonScope();
            }
            else
            {
                _container.Bind<IStoreObjects>().To<ObjectStore>().InSingletonScope();
                _container.Bind<IGetFlights>().To<FlightsService>().InSingletonScope();
            }
        }
Пример #28
0
        static void Main(string[] args)
        {
            DirEx direx;
            if (!ArgsBinder.TryParse(args, out direx))
            {
                throw new ArgsExeption(args);
            }

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

            IFileAction<string> fileAction = kernal.Get<IFileAction<string>>();
            fileAction.Output = kernal.Get<IFileActionResult<string>>();

            direx.OnFile += Direx_OnFileAction;
            direx.OnDirectory += Direx_OnDirectory;
            direx.Action(fileAction);

            if (fileAction.Output is IDisposable)
                ((IDisposable)fileAction.Output).Dispose();

#if DEBUG
            Cmd.ReadKey();
#endif
        }
        public static void Main()
        {
            // Simulate heavy load, collect frequently
            var task = new Task(() =>
            {
                while (true)
                {
                    Thread.Sleep(500);

                    Console.WriteLine("test");
                    GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
                    GC.WaitForPendingFinalizers();
                }
            });

            task.Start();

            var settings = new NinjectSettings {CachePruningInterval = new TimeSpan(0, 0, 5)};
            IKernel kernel = new StandardKernel(settings, new NinjectBindingsModule());

            PrintLoadedModules(kernel);

            var processor = kernel.Get<IMainProcessor>();
            processor.ProcessOnce();
            processor.ProcessOnce(); // second time is successful just as much
            Thread.Sleep(5000);

            var processor2 = kernel.Get<IMainProcessor>();
            processor2.ProcessOnce(); // ScopeDisposedException
        }
Пример #30
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);
        }
Пример #31
0
        static void Main(string[] args)
        {
            ArgParser.Parse(Config, args);

            Kernel = new StandardKernel();

            Kernel.Load(AppDomain.CurrentDomain.GetAssemblies());

            var repo = Kernel.Get<IRepository>();

            var serial = Kernel.Get<ISerializer>();

            var testResult = Kernel.Get<TestRunResult>();

            if (File.Exists("Config.cfg"))
                Config = serial.ReadFile<BehaviorConfiguration>("Config.cfg");

            repo.DataPath = Config.DataPath;

            testResult.StartTime = DateTime.Now;

            repo.GetAllStories(Config).ForEach(f => testResult.StoryResults.Add(f.Run(Kernel.Get<IRestClient>())));

            testResult.EndTime = DateTime.Now;

            (new TestRunReport(testResult.SetResult())).ToFile(Config.ResultFile);
        }
Пример #32
0
        /// <summary>
        /// Main 程序启动入口.
        /// </summary>
        /// <param name="args">命令行 参数</param>
        public static void Main(string[] args)
        {
            using (StandardKernel kernal = new StandardKernel(new MyModule()))
            {
                // 取得 停车场实现.
                ICarPark carpark = kernal.Get<ICarPark>();

                // 取得 车牌扫描实现.
                ICarNumberScan carNumSacn = kernal.Get<ICarNumberScan>();

                // 取得 车牌号码.
                string carNum = carNumSacn.GetCarNumber();

                for (int i = 1; i < 5; i++)
                {
                    // 进入车库.
                    carpark.InCarPark(carNum);

                    Thread.Sleep(1000 + i);

                    // 离开车库.
                    carpark.OutCarPark(carNum);
                }

                Console.ReadLine();
            }
        }
Пример #33
0
        public void make_order_with_context_factory_leaves_consistent_db()
        {
            UserTestData.PrepareUser(userId);

            int initialCount;
            int initialUserCount;

            using (var db = new MyContext())
            {
                initialCount     = db.Orders.Count(o => o.UserId == userId);
                initialUserCount = db.Users.Find(userId).OrdersCount;
            }

            MyContext.ResetCounters();

            using (var kernel = new Ninject.StandardKernel())
            {
                kernel.BindServices()
                .UseContextFromFactory()
                .UseSystemTransactions();

                var orderingService = kernel.Get <OrderingService>();
                orderingService.ShouldThrowAfterOrderAdd = true;

                try
                {
                    // ACT
                    MakeOrder(kernel.Get <IOrderingService>());
                    Assert.Fail("expected exception");
                }
                catch
                {
                    // ignore
                }
            }

            Assert.AreEqual(1, MyContext.TotalInstancesCreated);
            Assert.AreEqual(0, MyContext.InstanceCount);

            using (var db = new MyContext())
            {
                var user        = db.Users.Find(userId);
                var ordersCount = db.Orders.Count(o => o.UserId == userId);

                Assert.AreEqual(initialUserCount, user.OrdersCount);
                Assert.AreEqual(initialCount, ordersCount);
            }
        }
Пример #34
0
 public object Ninject()
 {
     using (var kernel = new Ninject.StandardKernel())
     {
         return(kernel.Get <T>());
     }
 }
Пример #35
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));
        }
Пример #36
0
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var user = filterContext.HttpContext.Session.GetCurrentUser();

            if (user == null || user.Uid <= 0)
            {
                ICookieService cookieService = new Flh.Web.CookieServiceImpl();
                var            cookieUser    = cookieService.User;
                if (cookieUser != null)
                {
                    try
                    {
                        IKernel ninjectKernel = new Ninject.StandardKernel(new Ninject.NinjectSettings()
                        {
                            DefaultScopeCallback = ctx => System.Web.HttpContext.Current
                        },
                                                                           new Flh.Business.Inject.DataModule(),
                                                                           new Flh.Business.Inject.ServiceModule()
                                                                           );

                        IUserManager userManager = ninjectKernel.Get <IUserManager>();
                        var          userService = userManager.Login(cookieUser.un, cookieUser.pwd, filterContext.HttpContext.Request.GetCurrentIP());
                        var          entry       = new UserSessionEntry
                        {
                            Name = userService.Name,
                            Uid  = userService.Uid
                        };
                        filterContext.HttpContext.Session.SetCurrentUser(entry);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
Пример #37
0
        public void Sample()
        {
            IKernel kernel = new Ninject.StandardKernel();

            kernel.Bind <ILogger>().To <ConsoleLogger>();
            ILogger logger = kernel.Get <ILogger>();
        }
Пример #38
0
        public void DoIt()
        {
            using (var kernel = new Ninject.StandardKernel())
            {
                kernel.Load <Nailhang.Mongodb.Module>();
                kernel.Rebind <Nailhang.Mongodb.MongoConnection>()
                .ToConstant(new MongoConnection
                {
                    ConnectionString = "mongodb://192.168.0.32",
                    DbName           = "nail_tests"
                });


                var ms = kernel.Get <IModulesStorage>();
                ms.StoreModule(new IndexBase.Module
                {
                    Assembly              = "lala",
                    Description           = "big lala",
                    FullName              = "very big lala",
                    InterfaceDependencies = new IndexBase.TypeReference[] { },
                    Interfaces            = new IndexBase.ModuleInterface[] { },
                    ModuleBinds           = new IndexBase.TypeReference[] { },
                    ObjectDependencies    = new IndexBase.TypeReference[] { },
                    Objects      = new IndexBase.ModuleObject[] { },
                    Significance = Significance.High
                });

                Assert.IsNotEmpty(ms.GetModules().ToArray());
                ms.DropModules("NOTREALNAMESPACE");
                Assert.IsNotEmpty(ms.GetModules().ToArray());
                ms.DropModules("");
                Assert.IsEmpty(ms.GetModules().ToArray());
            }
        }
Пример #39
0
        public void update_value_object_with_direct_context()
        {
            UserTestData.PrepareUser(userId);

            string houseNo = Guid.NewGuid().ToString("n");

            using (var kernel = new Ninject.StandardKernel())
            {
                kernel.ConfigureDirectContext();

                var orderingService = kernel.Get <IOrderingService>();

                // ACT
                orderingService.SetUserAddress(userId, new Address()
                {
                    City    = "Poznań",
                    HouseNo = houseNo,
                    Street  = "Brzęczyszczykiewicza"
                });
            }

            using (var db = new MyContext())
            {
                var user = db.Users.FirstOrDefault(u => u.Id == userId);

                // ups, we updated the object, but didn't reattach it to the new context!
                AssertThat.AreEqual(houseNo, user.Address.HouseNo);
            }
        }
        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);
        }
Пример #41
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();
     }
 }
Пример #42
0
        public static IEnumerable <object[]> GetContainerAdapters()
        {
            yield return(new object[] { (ResolverFactory)(c =>
                {
                    var container = new DefaultServiceContainer();
                    c(container);
                    return container.Resolve <IServiceResolver>();
                }) });

            yield return(new object[] { (ResolverFactory)(c =>
                {
                    var container = new LightInjectContainer();
                    c(new LightInjectAdapter(container));
                    return container.GetInstance <IServiceResolver>();
                }) });

            yield return(new object[] { (ResolverFactory)(c =>
                {
                    var container = new SimpleInjectorContainer {
                        Options = { AllowOverridingRegistrations = true }
                    };
                    c(new SimpleInjectorAdapter(container));
                    return container.GetInstance <IServiceResolver>();
                }) });

            yield return(new object[] { (ResolverFactory)(c =>
                {
                    var container = new StructureMapContainer(r => c(new StructureMapAdapter(r)));
                    return container.GetInstance <IServiceResolver>();
                }) });

            yield return(new object[] { (ResolverFactory)(c =>
                {
                    var containerBuilder = new ContainerBuilder();
                    c(new AutofacAdapter(containerBuilder));
                    var container = containerBuilder.Build();
                    return container.Resolve <IServiceResolver>();
                }) });

#if NETFX
            yield return(new object[] { (ResolverFactory)(c =>
                {
                    var container = new WindsorContainer();
                    c(new WindsorAdapter(container));
                    return container.Resolve <IServiceResolver>();
                }) });

            yield return(new object[] { (ResolverFactory)(c =>
                {
                    var container = new NinjectContainer();
                    c(new NinjectAdapter(container));
                    return container.Get <IServiceResolver>();
                }) });
#endif
        }
Пример #43
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>());
        }
Пример #44
0
        public void make_order_with_context_factory()
        {
            UserTestData.PrepareUser(userId);

            string itemName = $"item-{Guid.NewGuid()}";
            int    initialCount;
            int    initialUserCount;

            using (var db = new MyContext())
            {
                initialCount     = db.Orders.Count(o => o.UserId == userId);
                initialUserCount = db.Users.Find(userId).OrdersCount;
            }

            MyContext.ResetCounters();

            using (var kernel = new Ninject.StandardKernel())
            {
                kernel.BindServices()
                .UseContextFromFactory()
                .UseSystemTransactions();

                var orderingService = kernel.Get <OrderingService>();

                // ACT
                MakeOrder(kernel.Get <IOrderingService>(), itemName);
            }

            // each call to dbcontextfactory.create will create a new instance
            Assert.AreEqual(3, MyContext.TotalInstancesCreated);
            Assert.AreEqual(0, MyContext.InstanceCount);

            using (var db = new MyContext())
            {
                var user        = db.Users.Find(userId);
                var ordersCount = db.Orders.Count(o => o.UserId == userId);

                Assert.AreEqual(initialUserCount + 1, user.OrdersCount);
                Assert.AreEqual(initialCount + 1, ordersCount);
            }
        }
Пример #45
0
        /// <summary>
        ///     The main entry point of the program. This method initializes the composition root and then launches the game session.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            System.Console.Title = "Card Game";

            var kernel = new Ninject.StandardKernel();

            kernel.Load(System.Reflection.Assembly.GetExecutingAssembly());

            var gameSessionManager = kernel.Get <CardGameSessionManager>();

            gameSessionManager.BeginSession();
        }
        public void RegisterRealService()
        {
            using (var standardKernel = new Ninject.StandardKernel())
            {
                NinjectAuto.Register(Contracts.AssemblyInfo.GetExecutingAssembly(), Services.AssemblyInfo.GetExecutingAssembly(), standardKernel);

                var service = standardKernel.Get <IService>();

                string writeSomething = service.WriteSomething();

                Assert.AreEqual(writeSomething, "Real Service");
            }
        }
Пример #47
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);
        }
Пример #48
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>());
        }
Пример #49
0
 public WCFSorter()
 {
     try
     {
         string[] type_of_sorter = System.IO.File.ReadAllLines(@"Sorter.txt");
         var      kernel         = new Ninject.StandardKernel();
         kernel.Load(type_of_sorter[0]);
         sorter = kernel.Get <ISorter>();
     }
     catch (Exception e)
     {
         System.Console.WriteLine(e.Message);
         System.Console.ReadLine();
     }
 }
Пример #50
0
        public void InitApp()
        {
            //инициализация Ninject
            var kernel = new Ninject.StandardKernel(new ViewModel.Ninject.NinjectMainModule());

            _mainViewModel = kernel.Get <MainViewModel>();
            MainWindow     = new MainWindow()
            {
                DataContext = _mainViewModel
            };
            MainWindow.Closed += (s, e) =>
            {
                _mainViewModel.Dispose();
            };
            MainWindow.Show();
        }
Пример #51
0
 public int[] Sort(int[] array)
 {
     try
     {
         var kernel = new Ninject.StandardKernel();
         kernel.Load("Sort.xml");
         IWCFSorter sorter = kernel.Get <IWCFSorter>();
         return(sorter.Sort(array));
     }
     catch (Exception e)
     {
         System.Console.WriteLine(e.Message);
         System.Console.ReadLine();
         return(null);
     }
 }
Пример #52
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();
        }
Пример #53
0
        public static void Start()
        {
            log4net.Config.XmlConfigurator.Configure();

            var kernal = new Ninject.StandardKernel();

            kernal.Load(new[] { Assembly.GetExecutingAssembly() });
            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernal);


            var applicationConfigurationProvider = kernal.Get <IApplicationConfigurationProvider>();

            applicationConfigurationProvider.SourceCodeIndexPath.EnsureDirectoryExists();
            var writerLockPath = Path.Combine(applicationConfigurationProvider.SourceCodeIndexPath, "write.lock");

            if (File.Exists(writerLockPath))
            {
                File.Delete(writerLockPath);
            }
        }
Пример #54
0
        public void make_order_with_direct_context()
        {
            UserTestData.PrepareUser(userId);

            string itemName = $"item-{Guid.NewGuid()}";
            int    initialCount;
            int    initialUserCount;

            using (var db = new MyContext())
            {
                initialCount     = db.Orders.Count(o => o.UserId == userId);
                initialUserCount = db.Users.Find(userId).OrdersCount;
            }

            MyContext.ResetCounters();

            using (var kernel = new Ninject.StandardKernel())
            {
                kernel.BindServices()
                .UseContextDirectly()
                .UseNoTransactions();

                MakeOrder(kernel.Get <IOrderingService>(), itemName);
            }

            Assert.AreEqual(1, MyContext.TotalInstancesCreated);
            Assert.AreEqual(0, MyContext.InstanceCount);

            using (var db = new MyContext())
            {
                var user        = db.Users.Find(userId);
                var ordersCount = db.Orders.Count(o => o.UserId == userId);

                Assert.AreEqual(initialUserCount + 1, user.OrdersCount);
                Assert.AreEqual(initialCount + 1, ordersCount);
            }
        }
Пример #55
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);
            }
        }
        public void update_related_entity_with_direct_context()
        {
            UserTestData.PrepareUser(userId);

            string itemName = $"item-{Guid.NewGuid()}";

            using (var kernel = new Ninject.StandardKernel())
            {
                kernel.ConfigureDirectContext();

                var orderingService = kernel.Get <IOrderingService>();

                // ACT
                orderingService.SetUserPreferences(userId, itemName);
            }

            using (var db = new MyContext())
            {
                var user = db.Users.Include(u => u.UserPreferences).FirstOrDefault(u => u.Id == userId);

                // ups, we updated the object, but didn't reattach it to the new context!
                AssertThat.AreEqual(itemName, user.UserPreferences.FavoriteProduct);
            }
        }
Пример #57
0
    static void Main(string[] args)
    {
        var kernel = new Ninject.StandardKernel(new Module());

        kernel.Get <Simple>();
    }
Пример #58
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);
        }
Пример #59
0
        static void Main(string[] args)
        {
            //测试搜索
            //int count;
            //var ps = ProductSearchHelper.Search(new ProductSearchArgs { Keyword="红色纽扣",ClassNo="0002"}, out count);
            //return;
            Console.WriteLine("\n\n正在准备更新索引...");
            var fileName = "updateIndexMaxPid.txt";
            var kernel   = new Ninject.StandardKernel(
                new Flh.Business.Inject.DataModule()
                , new Flh.Business.Inject.ServiceModule()
                , new FileModule());
            var productManager = kernel.Get <Flh.Business.IProductManager>();
            var searchManager  = kernel.Get <Flh.Business.IProductSearchManager>();

            long maxPid    = 0;
            var  maxEntity = productManager.AllProducts.OrderByDescending(p => p.pid).FirstOrDefault();

            if (maxEntity != null)
            {
                maxPid = maxEntity.pid;
            }

            while (true)
            {
                //获取上次的索引更新的进度
                long minPid = 0;
                if (File.Exists(fileName))
                {
                    minPid = long.Parse(File.ReadAllText(fileName));
                }
                else
                {
                    minPid = 0;
                }
                if (minPid > 0)
                {
                    Console.WriteLine("\n接着上次的进度,从" + minPid + "开始更新");
                }
                else
                {
                    Console.WriteLine("\n从零开始更新索引");
                }

                //查出还没更新索引的产品
                var products = productManager.AllProducts.Where(d => d.pid > minPid)
                               .OrderBy(d => d.pid)
                               .Take(30).ToArray();
                if (products.Any())
                {
                    foreach (var product in products)
                    {
                        if (product.enabled)
                        {
                            searchManager.UpdateSearchIndex(product);//更新索引
                        }
                        else
                        {
                            searchManager.DeleteIndex(product.pid);          //删除索引
                        }
                        File.WriteAllText(fileName, product.pid.ToString()); //保存索引进度
                        Console.WriteLine("正在更新索引:" + product.pid + "/" + maxPid + " " + product.name);
                    }
                }
                else
                {
                    File.WriteAllText(fileName, "0"); //清空索引进度
                    Console.WriteLine("\n搜索引擎更新完毕!按回车键退出");
                    break;
                }
            }
            Console.Read();
        }
Пример #60
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();
        }