public void Run(IConfiguration configuration, IWebEnvironment environment)
 {
     var module = CreateModules().ToArray();
     if (module.Length == 0) return;
     var kernel = new StandardKernel(module);
     configuration.Container = new NinjectContainer(kernel);
 }
        public List<FeatureInfo> GetBindingInformations(INinjectModule module)
        {
            List<FeatureInfo> bindingsFeatureInfoList = new List<FeatureInfo>();

            IKernel kernel = new StandardKernel();
            module.OnLoad(kernel);

            List<KeyValuePair<Type, ICollection<IBinding>>> typeBindingInfo = GetBindings(kernel, module.Name);

            foreach (KeyValuePair<Type, ICollection<IBinding>> typeBinding in typeBindingInfo)
            {
                FeatureInfo bindingInterface = new FeatureInfo(typeBinding.Key, null, null, FeatureType.BindingInterface);

                foreach (IBinding binding in typeBinding.Value)
                {
                    ContextMock contextMock = new ContextMock(kernel);

                    IProvider provider = binding.ProviderCallback(contextMock);

                    FeatureInfo bindingInterfaceImpl = new FeatureInfo(provider.Type, null, null, FeatureType.BindingImpl);
                    bindingInterfaceImpl.SetBindingType(binding.Target);

                    bindingInterface.AddDependency(bindingInterfaceImpl);
                }

                bindingsFeatureInfoList.Add(bindingInterface);
            }

            return bindingsFeatureInfoList;
        }
        public void InstanceIsDeactivatedWhenItLeavesScope()
        {
            Barracks barracks;
            using ( var kernel = new StandardKernel() )
            {
                kernel.Bind<Barracks>()
                    .ToSelf()
                    .InSingletonScope()
                    .OnActivation(instance =>
                                    {
                                        instance.Warrior = new FootSoldier();
                                        instance.Weapon = new Shuriken();
                                    })
                    .OnDeactivation(instance =>
                                    {
                                        instance.Warrior = null;
                                        instance.Weapon = null;
                                    });

                barracks = kernel.Get<Barracks>();
                barracks.Warrior.ShouldNotBeNull();
                barracks.Warrior.ShouldBeInstanceOf<FootSoldier>();
                barracks.Weapon.ShouldNotBeNull();
                barracks.Weapon.ShouldBeInstanceOf<Shuriken>();
            }
            barracks.Warrior.ShouldBeNull();
            barracks.Weapon.ShouldBeNull();
        }
 public void IsNotOverlappingWhenOneBoundingBox()
 {
     var kernel = new StandardKernel();
     kernel.Load<ProtogameCoreModule>();
     var boundingBoxUtilities = kernel.Get<IBoundingBoxUtilities>();
     _assert.False(boundingBoxUtilities.Overlaps(this.CreateBoundingBox(200, 200, 16, 16)));
 }
Example #5
0
 public void ReplaceMapper() {
     var c = new StandardKernel();
     var mapper = new global::SolrNet.Tests.Mocks.MReadOnlyMappingManager();
     c.Load(new SolrNetModule("http://localhost:8983/solr") {Mapper = mapper});
     var m = c.Get<IReadOnlyMappingManager>();
     Assert.AreSame(mapper, m);
 }
        public FactoryTests()
        {
            this.kernel = new StandardKernel();
#if NO_ASSEMBLY_SCANNING
            this.kernel.Load(new FuncModule());
#endif        
        }
Example #7
0
 static Container()
 {
     if (Kernel == null)
     {
         Kernel = new StandardKernel(new ClientModule());
     }
 }
        public void ManyPublishersManySubscribers()
        {
            using ( var kernel = new StandardKernel() )
            {
                var pub1 = kernel.Get<PublisherMock>();
                var pub2 = kernel.Get<PublisherMock>();
                Assert.NotNull( pub1 );
                Assert.NotNull( pub2 );

                var sub1 = kernel.Get<SubscriberMock>();
                var sub2 = kernel.Get<SubscriberMock>();
                Assert.NotNull( sub1 );
                Assert.NotNull( sub2 );

                Assert.True( pub1.HasListeners );
                Assert.True( pub2.HasListeners );
                Assert.Null( sub1.LastMessage );
                Assert.Null( sub2.LastMessage );

                pub1.SendMessage( "Hello, world!" );
                Assert.Equal( sub1.LastMessage, "Hello, world!" );
                Assert.Equal( sub2.LastMessage, "Hello, world!" );

                sub1.LastMessage = null;
                sub2.LastMessage = null;
                Assert.Null( sub1.LastMessage );
                Assert.Null( sub2.LastMessage );

                pub2.SendMessage( "Hello, world!" );
                Assert.Equal( sub1.LastMessage, "Hello, world!" );
                Assert.Equal( sub2.LastMessage, "Hello, world!" );
            }
        }
Example #9
0
        public FactoryProviderContext()
        {
            contextMock = new Mock<IContext>();
            kernel = new StandardKernel();

            contextMock.SetupGet(c => c.Kernel).Returns(kernel);
        }
        public void TransientBindingsWork()
        {
            var kernel = new StandardKernel();

            kernel.Get(
                typeof (IInput),
                null,
                null,
                null,
                null,
                null,
                new Dictionary<Type, List<IMapping>>
                {
                    {
                        typeof (IInput), new List<IMapping>
                        {
                            new DefaultMapping(
                                typeof(DefaultInput),
                                null,
                                false,
                                null,
                                null,
                                false,
                                false,
                                null)
                        }
                    }
                });
        }
 public void IsNotOverlappingWhenNoBoundingBoxes()
 {
     var kernel = new StandardKernel();
     kernel.Load<ProtogameCoreModule>();
     var boundingBoxUtilities = kernel.Get<IBoundingBoxUtilities>();
     _assert.False(boundingBoxUtilities.Overlaps());
 }
Example #12
0
 public void Ping_And_Query()
 {
     var c = new StandardKernel();
     c.Load(new SolrNetModule("http://localhost:8983/solr"));
     var solr = c.Get<ISolrOperations<Entity>>();
     solr.Ping();
     Console.WriteLine(solr.Query(SolrQuery.All).Count);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="NinjectTraceLogger" /> class.
        /// </summary>
        public NinjectTraceLogger()
        {
            var kernel = new StandardKernel();

            this.logger = kernel.Get<ILoggerFactory>().GetCurrentClassLogger();

            this.beginTraces = new List<TraceRecord>();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="UsageHandler" /> class.
        /// </summary>
        public UsageHandler()
        {
            var kernel = new StandardKernel();

            var logfactory = kernel.Get<ILoggerFactory>();

            this.Log = logfactory.GetCurrentClassLogger();
        }
Example #15
0
 public void ReplaceMapper()
 {
     var c = new StandardKernel();
     var mapper = MockRepository.GenerateMock<IReadOnlyMappingManager>();
     c.Load(new SolrNetModule("http://localhost:8983/solr") {Mapper = mapper});
     var m = c.Get<IReadOnlyMappingManager>();
     Assert.AreSame(mapper, m);
 }
 public void IsNotOverlappingWhenSameBoundingBoxAndNoOtherBoxes()
 {
     var kernel = new StandardKernel();
     kernel.Load<ProtogameCoreModule>();
     var boundingBoxUtilities = kernel.Get<IBoundingBoxUtilities>();
     var entity = this.CreateBoundingBox(200, 200, 16, 16);
     _assert.False(boundingBoxUtilities.Overlaps(entity, entity));
 }
		protected override IKernel CreateKernel()
		{
			var kernel = new StandardKernel();

			kernel.Load<PersistenceModule>();

			return kernel;
		}
        public void SetUp()
        {
            IKernel kernel = new StandardKernel(new NinjectSettings {LoadExtensions = false});
            kernel.Load(new LinFuModule());
            kernel.Load(new TransactionalAnnotationTestModule());

            _targetService = kernel.Get<ITargetService>();
            _interceptor = (TestTransactionInterceptor) kernel.Get<ITransactionInterceptor>();
        }
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }
 public void IsOverlappingWhenDifferentBoundingBoxes()
 {
     var kernel = new StandardKernel();
     kernel.Load<ProtogameCoreModule>();
     var boundingBoxUtilities = kernel.Get<IBoundingBoxUtilities>();
     _assert.True(boundingBoxUtilities.Overlaps(
         this.CreateBoundingBox(200, 200, 16, 16),
         this.CreateBoundingBox(200, 200, 16, 16)));
 }
        /// <summary>
        /// Sets up the tests.
        /// </summary>
        public void SetUp()
        {
            this.kernel = new StandardKernel();
#if SILVERLIGHT
            this.kernel.Load(new NamedScopeModule());
            this.kernel.Load(new ContextPreservationModule());
            this.kernel.Load(new EventBrokerModule());
#endif
        }
        public WhenReleasingAnObject()
        {
            this.kernel = new StandardKernel();

            this.kernel.Bind<Foo>().ToSelf().InSingletonScope();
            this.kernel.Bind<Bar>().ToSelf().InScope(ctx => this.foo);

            this.foo = this.kernel.Get<Foo>();
        }
        protected override IServiceLocator CreateServiceLocator() {
            var kernel = new StandardKernel();
            var simpleType = typeof(SimpleLogger);
            kernel.Bind<ILogger>().To<SimpleLogger>().Named(simpleType.FullName);

            var loggerType = typeof(ComplexLogger);
            kernel.Bind<ILogger>().To<ComplexLogger>().Named(loggerType.FullName);
            return new NinjectServiceLocator(kernel);
        }
 public void CanResolveMatchInMiddleOfInterface()
 {
     var regexBindingGenerator = new RegexBindingGenerator("(I)(?<name>.+)(View)");
     using (IKernel kernel = new StandardKernel())
     {
         regexBindingGenerator.Process(typeof(DefaultView), StandardScopeCallbacks.Transient, kernel);
         kernel.GetBindings(typeof(IDefaultView)).Count().ShouldBe(1);
         kernel.Get<IDefaultView>().ShouldBeInstanceOf<DefaultView>();
     }
 }
Example #25
0
        public static void Main(string[] args)
        {
            var kernel = new StandardKernel();

            var featureModuleLoader = new FeatureModuleLoader(kernel);

            featureModuleLoader.Load(new MyAppFeature());

            var thing = kernel.Get<MyInfrastructureThing>();
        }
 private IKernel CreateKernel()
 {
     var kernel = new StandardKernel();
     kernel.Bind<IEntityFactory>().ToFactory();
     kernel.Bind<IPlayer>().To<Player>();
     kernel.Bind<INetworkingPlayer>().To<NetworkingPlayer>();
     kernel.Bind<IMovement>().To<DefaultMovement>();
     kernel.Bind<IInput>().To<DefaultInput>();
     return kernel;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="MissingBindingLogger" /> class.
        /// </summary>
        public MissingBindingLogger()
        {
            // Wire up events
            BindingMissing += this.OnBindingMissing; 
            
            // Wire up logger
            var kernel = new StandardKernel();

            this.Log = kernel.Get<ILoggerFactory>().GetCurrentClassLogger();
        }
 public void CanResolveMatchInMiddleOfInterface()
 {
     var regexBindingGenerator = new RegexBindingGenerator( "(I)(?<name>.+)(View)" );
     using ( IKernel kernel = new StandardKernel() )
     {
         regexBindingGenerator.Process( typeof (DefaultView), kernel );
         Assert.Equal( kernel.GetBindings( typeof (IDefaultView) ).Count(), 1 );
         Assert.IsType( typeof (DefaultView), kernel.Get<IDefaultView>() );
     }
 }
        public void ConventionsCanBeUsedInModules()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Load<TestModule>();
                var instance = kernel.Get<IDefaultConvention>();

                instance.Should().NotBeNull();
                instance.Should().BeOfType<DefaultConvention>();
            }
        }
 private IKernel CreateKernel()
 {
     var kernel = new StandardKernel();
     kernel.Bind(typeof(IGenericFactory<,>)).ToFactory();
     kernel.Bind(typeof(IGeneric<,>)).To(typeof(DefaultGeneric<,>));
     kernel.Bind<IPlayer>().To<Player>();
     kernel.Bind<INetworkingPlayer>().To<NetworkingPlayer>();
     kernel.Bind<IMovement>().To<DefaultMovement>();
     kernel.Bind<IInput>().To<DefaultInput>();
     return kernel;
 }
Example #31
0
        private static void Main()
        {
            try
            {
                var container = new StandardKernel();
                container.Bind(x => x
                               .FromThisAssembly()
                               .SelectAllClasses()
                               .BindAllInterfaces());

                // start here
                container.Rebind <ImageSettings>().ToSelf().InSingletonScope();
                container.Rebind <IImageHolder, PictureBoxImageHolder>()
                .To <PictureBoxImageHolder>()
                .InSingletonScope();
                container.Rebind <IObjectSerializer>().To <XmlObjectSerializer>();
                container.Rebind <IBlobStorage>().To <FileBlobStorage>();
                container.Rebind <AppSettings, IImageDirectoryProvider>()
                .ToMethod(context => container.Get <SettingsManager>().Load());


                container.Rebind <Palette>().ToSelf().InSingletonScope();
                container.Rebind <IDragonPainterFactory>().ToFactory();


                // container.Bind<KochPainter>().ToSelf().InSingletonScope();

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(container.Get <MainForm>());
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);

                throw;
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.WriteLine("Juego de lucha");

            /*
             * //Inyección de dependencias manual
             * var guerrero = new Guerrero(new Espada());
             * guerrero.Nombre="Guerrero";
             * guerrero.Pelear();
             * var hechicero = new Hechicero(new Varita());
             * hechicero.Nombre="Hechicero";
             * hechicero.Pelear();
             * var combate = new Lucha(guerrero,hechicero);
             * combate.Ganador();
             */

            //Inyección de dependencias con Ninject
            var kernel = new StandardKernel();

            kernel.Bind <IArma>().To <Espada>();
            var guerrero = kernel.Get <Guerrero>();

            guerrero.Nombre = "Guerrero";
            guerrero.Pelear();

            var kernel2 = new StandardKernel();

            kernel2.Bind <IArma>().To <Varita>();
            var hechicero = kernel2.Get <Hechicero>();

            hechicero.Nombre = "Hechicero";
            hechicero.Pelear();

            var combate = new Lucha(guerrero, hechicero);

            combate.Ganador();
        }
Example #33
0
        /// <summary>
        /// Generates the kernel with all the contract/concrete implementation bindings
        /// </summary>
        /// <returns>The kernel.</returns>
        private static IKernel GenerateKernel()
        {
            var configService = new ConfigurationService();

            trainingStart = Convert.ToDateTime(configService.Get(ConfigurationKey.TrainingStartDate));
            trainingEnd   = Convert.ToDateTime(configService.Get(ConfigurationKey.TrainingEndDate));

            IKernel _kernel = new StandardKernel();

            _kernel.Bind <ILogger>().ToMethod(x => LoggerService.GetInstance());
            _kernel.Bind <IConfigurationService>().To <ConfigurationService>();
            _kernel.Bind <IFileIOService>().To <FileIOService>();

            _kernel.Bind <ISession>()
            .ToMethod(x => new MySQLConnection(_kernel.Get <IConfigurationService>()).getSession())
            .InThreadScope();

            _kernel.Bind <IRepository>().To <Repository>();
            _kernel.Bind <ICSVReaderService>().To <CSVReaderService>();
            _kernel.Bind <ICSVParseStrategy>().To <IncidentCSVParseStrategy>();

            _kernel.Bind <IOfficerService>().To <OfficerService>();
            _kernel.Bind <ILocationService>().To <LocationService>();
            _kernel.Bind <IIncidentGradingService>().To <IncidentGradingService>();
            _kernel.Bind <IIncidentOutcomeService>().To <IncidentOutcomeService>();
            _kernel.Bind <IIncidentBacklogService>().To <IncidentBacklogService>();
            _kernel.Bind <IIncidentService>().To <IncidentService>();

            _kernel.Bind <IDistanceMeasure>().To <EuclideanDistance>();
            _kernel.Bind <IClusteringService>().To <DJClusterAlgorithm>();
            _kernel.Bind <IMixedMarkovModel>().To <MixedMarkovModel>()
            .WithConstructorArgument("start", trainingStart)
            .WithConstructorArgument("end", trainingEnd);

            _kernel.Bind <IModelEvaluation>().To <ModelEvaluation>();

            return(_kernel);
        }
Example #34
0
        public static void Main(string[] args)
        {
            FreeConsole();

            using (IKernel kernel = new StandardKernel())
            {
                try
                {
                    CreateLogger();
                    LoggerFactory.GetLogger().Info(string.Join("", Enumerable.Repeat("#", 80)));
                    LoggerFactory.GetLogger().Info("Application starts!");
                    LoggerFactory.GetLogger().Info("Loading kernel modules... ");
                    LoadModules(kernel);
                    LoggerFactory.GetLogger().Info("Kernel modules loaded");

                    var viewModelFactory = kernel.Get <ViewModelLocator>();
                    var application      = CreateApplication(viewModelFactory);

                    var mainWindowViewModel = viewModelFactory.CreateViewModel <MainWindowViewModel>();

                    var mainWindow = kernel.Get <MainWindow>();
                    mainWindow.DataContext = mainWindowViewModel;

                    LoggerFactory.GetLogger().Info(string.Join("", Enumerable.Repeat("#", 80)));

                    application.Run(mainWindow);
                    application.Shutdown();
                    LoggerFactory.GetLogger().Info("Application ended...");
                    LoggerFactory.GetLogger().Info("\n\n\n\n");
                }
                catch (Exception e)
                {
                    LoggerFactory.GetLogger().Error("Unhandled exception", e);

                    throw e;
                }
            }
        }
Example #35
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();


            config.EnableCors(new EnableCorsAttribute("http://localhost:53695", "*", "*"));
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            var kernel = new StandardKernel(new NinjectConfigModule(), new SiteAutoMapperModule(), new ServiceAutoMapperModule());

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.UseOAuthBearerTokens(kernel.Get <IOAuthAuthorizationServerOptions>().GetOptions());

            app.UseNinjectMiddleware(() => kernel)
            .UseNinjectWebApi(config);
        }
Example #36
0
        public static void Run(string[] args)
        {
            // Initialize Ninject (the DI framework)
            var kernel = new StandardKernel(new CommonModule(), new ConsoleModule());

            Paths.ClearTemp();

            // Parse the command-line arguments (and display help text if appropriate)
            var options = new AutomatedScanningOptions();

            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                return;
            }

            // Start a pending worker process
            WorkerManager.Init();

            // Run the scan automation logic
            var scanning = kernel.Get <AutomatedScanning>(new ConstructorArgument("options", options));

            scanning.Execute().Wait();
        }
Example #37
0
        private static void Main(string[] args)
        {
            var kernel = new StandardKernel();

            // Ninject?! Surely using it is overkill for such a simple app?
            // Perhaps but I wanted to see if I could use Ninject to discover language
            // specific generators. Adding support for a new language should just mean
            // adding a code generator implementation for that language; no manual
            // wiring necessary.
            kernel.Bind(x => x
                        .FromThisAssembly()
                        .SelectAllClasses()
                        .BindAllInterfaces());

            var generator = kernel.Get <ICodeGenerator>();

            // I don’t anticipate definition sources to be constructed using Ninject.
            // They will likely be constructed by factories because they'll need to
            // know information like the path to a file containing definitions.
            var definitionsSource = new TestDefinitionsSource();

            generator.GenerateCode(new[] { definitionsSource });
        }
Example #38
0
        public void Get_KernelDefaultsToSingleton_AllFuncsReturnSameEventAggregator()
        {
            // This test depends on Ninject.Extensions.ContextPreservation being loaded.

            // Assemble
            var settings = new NinjectSettings()
            {
                DefaultScopeCallback = StandardScopeCallbacks.Singleton,
            };

            using (var k = new StandardKernel(settings))
            {
                Bind(k);

                // Act
                var root1 = k.Get <IRoot>();
                var root2 = k.Get <IRoot>();

                // Assert

                Assert.AreEqual(root1.ChildEventAggregator, root2.ChildEventAggregator);
            }
        }
Example #39
0
        public static StandardKernel LoadNinjectKernel(IEnumerable <Assembly> assemblies)
        {
            var standardKernel = new StandardKernel();

            foreach (var assembly in assemblies)
            {
                assembly
                .GetTypes()
                .Where(t =>
                       t.GetInterfaces()
                       .Any(i =>
                            i.Name == typeof(INinjectModuleBootstrapper).Name))
                .ToList()
                .ForEach(t =>
                {
                    var ninjectModuleBootstrapper =
                        (INinjectModuleBootstrapper)Activator.CreateInstance(t);

                    standardKernel.Load(ninjectModuleBootstrapper.GetModules());
                });
            }
            return(standardKernel);
        }
Example #40
0
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();

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

            string path = ConfigurationManager.AppSettings["DataDirectory"];

            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            kernel.Settings.Set("DbDedaultConnection", "DefaultConnection");

            try
            {
                RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <param name="getInjections"></param>
        /// <returns>The created kernel.</returns>
        public static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();

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

                RegisterServices(kernel);

                // Install our Ninject-based IDependencyResolver into the Web API config
                GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Example #42
0
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            using (IKernel kernel = new StandardKernel(new MyBindings()))
            {
                var config = new JobHostConfiguration
                {
                    JobActivator = new MyJobActivator(kernel)
                };

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

                config.Queues.MaxDequeueCount = ConfigHelper.GetMaxDequeueCount();
                config.UseCore();

                var host = new JobHost(config);

                // The following code ensures that the WebJob will be running continuously
                host.RunAndBlock();
            }
        }
Example #43
0
File: Program.cs Project: rpe4a/di
        private static void Main()
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var container = new StandardKernel();

                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>();

                var mainForm = container.Get <MainForm>();
                Application.Run(mainForm);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        public void PropertyGetInterceptedBefore()
        {
            string testString = "empty";

            using (StandardKernel kernel = CreateDefaultInterceptionKernel())
            {
                kernel.InterceptBeforeGet <Mock>(
                    o => o.MyProperty,
                    i =>
                {
                    if (i.ReturnValue == null)
                    {
                        testString = "null";
                    }
                });

                var obj = kernel.Get <Mock>();

                testString.Should().Be("empty");
                obj.MyProperty.Should().Be("start");
                testString.Should().Be("null");
            }
        }
Example #45
0
        public static void Main(string[] args)
        {
            ConfigureLog();

            using (var kernel = new StandardKernel(new ZappModule()))
            {
                kernel.Bind <IFusionFilter>().To <FusionProcessRenameFilter>();

                var server = kernel.Get <IZappServer>();

                try
                {
                    server.StartAsync(CancellationToken.None)
                    .GetAwaiter()
                    .GetResult();
                }
                catch { }

                ThreadPool.QueueUserWorkItem((state) => ListenConsoleInput());

                resetEvent.WaitOne();
            }
        }
        /// <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>();

                kernel.Bind <IUserPasswordDAL>().To <UserPasswordSqlDAL>();
                kernel.Bind <IStaffDAL>().To <StaffSqlDAL>();
                kernel.Bind <IStudentDAL>().To <StudentSqlDAL>();
                kernel.Bind <IEmployerDAL>().To <EmployerSqlDAL>();

                RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Example #47
0
    static void Main(string[] args)
    {
        // these statements are here so that we can generate
        // results that display US currency values even though
        // the locale of our machines is set to the UK
        System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
        System.Threading.Thread.CurrentThread.CurrentCulture   = ci;
        System.Threading.Thread.CurrentThread.CurrentUICulture = ci;

        IKernel ninjectKernel = new StandardKernel();

        ninjectKernel.Bind <IValueCalculator>().To(typeof(LinqValueCalculator));
        ninjectKernel.Bind <IDiscountHelper>()
        .To(typeof(DefaultDiscountHelper)).WithConstructorArgument("discountParam", 50M);

        ninjectKernel.Bind <ShoppingCart>().ToSelf();    //.WithParameter("<parameterName", <paramvalue>);

        // get an instance of the ShoopingCart class
        ShoppingCart cart = ninjectKernel.Get <ShoppingCart>();

        // perform the calculation and write out the result
        Console.WriteLine("Total: {0:c}", cart.CalculateStockValue());
    }
Example #48
0
    static void Main()
    {
        #region ContainerConfiguration
        var configuration = new BusConfiguration();
        configuration.EndpointName("Samples.Ninject");

        var kernel = new StandardKernel();
        kernel.Bind<MyService>().ToConstant(new MyService());
        configuration.UseContainer<NinjectBuilder>(c => c.ExistingKernel(kernel));
        #endregion
        configuration.UseSerialization<JsonSerializer>();
        configuration.UsePersistence<InMemoryPersistence>();
        configuration.EnableInstallers();

        using (var bus = Bus.Create(configuration))
        {
            bus.Start();
            bus.SendLocal(new MyMessage());
            Console.WriteLine("Press any key to exit");
            Console.Read();

        }
    }
        public static void ConfigureSignalR(IAppBuilder app)
        {
            var kernel   = new StandardKernel();
            var resolver = new NinjectSignalRDependencyResolver(kernel);

            kernel.Bind <IStockTicker>().To <StockTicker>().InSingletonScope();
            kernel.Bind <IHubConnectionContext>()
            .ToMethod(context => resolver.Resolve <IConnectionManager>().GetHubContext <StockTickerHub>().Clients)
            .WhenInjectedInto <IStockTicker>();

            var config = new HubConfiguration()
            {
                Resolver = resolver
            };

            var heartBeat = GlobalHost.DependencyResolver.Resolve <ITransportHeartbeat>();
            var monitor   = new PresenceMonitor(heartBeat);

            monitor.StartMonitoring();

            //Using the ninject dependency resolver, the ITransportHeartbeat.GetConnections() in the PresenceMonitor never returns any connections
            app.MapSignalR(config);
        }
Example #50
0
 /// <summary>
 /// Initialize Agent ApplicationContext
 /// </summary>
 public AgentApplicationContext()
 {
     try
     {
         _kernel    = InitializeContainer();
         _baseUrl   = GetWebServerBaseUrl();
         _webServer = new WebServer.WebServer(_baseUrl);
         var importService = _kernel.Get <Services.IImportService>();
         MainForm = new MainForm(_webServer, importService);
     }
     catch (Exception caught)
     {
         logger.Fatal("Unable to Initialize Application Context", caught);
         MessageBox.Show("An unexpected error has occurred while trying to start " +
                         "the Crown of the Gods Data Collection Agent.  It is recommended to " +
                         "review the log files for more information.",
                         "Crown of the Gods - Agent Fatal Startup Error",
                         MessageBoxButtons.OK,
                         MessageBoxIcon.Error,
                         MessageBoxDefaultButton.Button1);
         Environment.FailFast("Unable to start!", caught);
     }
 }
Example #51
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>();
                kernel.Bind <IPerson>().To <PersonRepo>();
                kernel.Bind <ICar>().To <CarRepo>();
                //kernel.Bind<TestContext>().ToSelf().InRequestScope();
                kernel.Bind <TestContext>().ToSelf().InRequestScope();
                kernel.Bind <IHttpModule>().To <HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
        /// <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>();

                // Support Web API (nuget install WebAPIContrib.ioc.Ninject)
                //  Got an Entry Point Error doing this
                //GlobalConfiguration.Configuration.DependencyResolver =
                //   new NinjectResolver( kernel );

                RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Example #53
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>();

                // register all your dependencies on the kernel container
                RegisterServices(kernel);

                // register the dependency resolver passing the kernel container
                GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
        /// <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);

                kernel.Bind(x => { x.FromThisAssembly().SelectAllClasses().BindDefaultInterface(); });

                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Example #55
0
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var modules = new INinjectModule[]
            {
                new LoggingModule()
            };

            var kernel = new StandardKernel(modules);

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

                RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Example #56
0
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel(new WebModule());

            try
            {
                kernel.Bind <Func <IKernel> >().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind <IHttpModule>().To <HttpApplicationInitializationHttpModule>();
                var modules = new List <INinjectModule>
                {
                    new BusinessModule(),
                    new DataModule()
                };
                kernel.Load(modules);
                //RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Example #57
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);

                NinjectDependencyResolver ninjectResolver = new NinjectDependencyResolver(kernel);
                DependencyResolver.SetResolver(ninjectResolver);                        //MVC
                GlobalConfiguration.Configuration.DependencyResolver = ninjectResolver; //Web API

                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var settings = new NinjectSettings()
            {
                LoadExtensions = true
            };

            settings.ExtensionSearchPatterns = settings.ExtensionSearchPatterns.Union(new string[] { "Project.*.dll" }).ToArray();
            var kernel = new StandardKernel(settings);

            try
            {
                kernel.Bind <Func <IKernel> >().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind <IHttpModule>().To <HttpApplicationInitializationHttpModule>();
                RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Example #59
0
        public void AddSoundBoardCommandExecute__CallsNameDialogWithMainWindowAsParentParameter()
        {
            //Arrange
            MainWindow     expectedParent = new MainWindow();
            IDialogService mock           = MockRepository.GenerateMock <IDialogService>();
            IKernel        container      = new StandardKernel();

            container.Bind <MainWindow>().ToConstant(expectedParent);

            Target = CreateTarget(dialogService: mock, container: container);

            mock.Expect(service => service.NameDialog(
                            Arg <Window> .Is.Same(expectedParent),
                            Arg <string> .Is.Anything,
                            Arg <string> .Is.Anything,
                            Arg <string> .Is.Anything)).Return(string.Empty);

            //Act
            Target.Commands.AddSoundBoardCommand.Execute(null);

            //Assert
            mock.VerifyAllExpectations();
        }
Example #60
0
        private IKernel CreateComparison()
        {
            var kernel = new StandardKernel();

            //builder.Bind<IPerformanceMethodTest>().To<PerformanceMethodTest>();
            kernel.Bind <IPerformanceMethodTest>().To <PerformanceMethodTest>();
            //builder.Bind<IPerformanceMethodResultTest>().To((ctx) => PerformanceMethodTest.Method());
            kernel.Bind <IPerformanceMethodResultTest>().ToMethod((ctx) => PerformanceMethodTest.Method());
            //builder.Bind<IPerformanceConstructParam1Test>().To<PerformanceConstructParamTest>();
            kernel.Bind <IPerformanceConstructParam1Test>().To <PerformanceConstructParamTest>();
            //builder.Bind<IPerformanceConstructParam2Test>().To<PerformanceConstructParamTest>();
            kernel.Bind <IPerformanceConstructParam2Test>().To <PerformanceConstructParamTest>();
            //builder.Bind<IPerformanceConstructParam3Test>().To<PerformanceConstructParamTest>();
            kernel.Bind <IPerformanceConstructParam3Test>().To <PerformanceConstructParamTest>();
            //builder.Bind<IPerformanceConstructTest>().To<PerformanceConstructTest>();
            kernel.Bind <IPerformanceConstructTest>().To <PerformanceConstructTest>();
            //builder.Bind<IPerformanceSingletonTest>().To<PerformanceSingletonTest>().InSingletonScope();
            kernel.Bind <IPerformanceSingletonTest>().To <PerformanceSingletonTest>().InSingletonScope();
            //builder.Bind<IPerformanceInstanceTest>().To(new PerformanceInstanceTest());
            kernel.Bind <IPerformanceInstanceTest>().ToConstant(new PerformanceInstanceTest());

            return(kernel);
        }