Ejemplo n.º 1
1
        private static IMediator BuildMediator()
        {
            var kernel = new StandardKernel();
            kernel.Components.Add<IBindingResolver, ContravariantBindingResolver>();
            kernel.Bind(scan => scan.FromAssemblyContaining<IMediator>().SelectAllClasses().BindDefaultInterface());
            kernel.Bind(scan => scan.FromAssemblyContaining<Ping>().SelectAllClasses().BindAllInterfaces());
            kernel.Bind<TextWriter>().ToConstant(Console.Out);
            kernel.Bind<SingleInstanceFactory>().ToMethod(ctx => t => ctx.Kernel.Get(t));
            kernel.Bind<MultiInstanceFactory>().ToMethod(ctx => t => ctx.Kernel.GetAll(t));

            var mediator = kernel.Get<IMediator>();

            return mediator;
        }
        /// <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;
        }
        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);
        }
Ejemplo n.º 4
0
 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;
 }
Ejemplo n.º 5
0
        public void SpecificValueShouldBeUsedWhenMapped()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind<Shield>().ToSelf();
                kernel.Bind<ShieldColor>().ToConstant(ShieldColor.Blue);

                var shield = kernel.Get<Shield>();
                shield.ShouldNotBeNull();
                shield.Color.ShouldBe(ShieldColor.Blue);
            }
        }
Ejemplo n.º 6
0
        public void FirstAvailableWithBindingAvailableIsUsed()
        {
            using ( IKernel kernel = new StandardKernel() )
            {
                kernel.Bind<Barracks>().ToSelf();
                kernel.Bind<IWeapon>().To<Sword>();

                var barracks = kernel.Get<Barracks>();
                barracks.ShouldNotBeNull();
                barracks.Warrior.ShouldBeNull();
                barracks.Weapon.ShouldNotBeNull();
            }
        }
        public void FirstAvailableWithBindingAvailableIsUsed()
        {
            using ( IKernel kernel = new StandardKernel() )
            {
                kernel.Bind<Barracks>().ToSelf();
                kernel.Bind<IWeapon>().To<Sword>();

                var barracks = kernel.Get<Barracks>();
                Assert.NotNull( barracks );
                Assert.Null( barracks.Warrior );
                Assert.NotNull( barracks.Weapon );
            }
        }
        public void CtorWithMostDependenciesIsUsedWhenBindingsAreAvailable()
        {
            using ( IKernel kernel = new StandardKernel() )
            {
                kernel.Bind<Barracks>().ToSelf();
                kernel.Bind<IWeapon>().To<Sword>();
                kernel.Bind<IWarrior>().To<Samurai>();

                var barracks = kernel.Get<Barracks>();
                Assert.NotNull( barracks );
                Assert.NotNull( barracks.Warrior );
                Assert.NotNull( barracks.Warrior.Weapon );
                Assert.NotNull( barracks.Weapon );
            }
        }
Ejemplo n.º 9
0
        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();
        }
Ejemplo n.º 10
0
        public void DefaultValuesShouldNotInflunceInjectionsToOtherTypes()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind<Shield>().ToSelf();
                kernel.Bind<KiteShield>().ToSelf();

                var shield1 = kernel.Get<Shield>();
                var shield2 = kernel.Get<KiteShield>();

                shield1.ShouldNotBeNull();
                shield1.Color.ShouldBe(ShieldColor.Red);

                shield2.ShouldNotBeNull();
                shield2.Color.ShouldBe(ShieldColor.Orange);
            }
        }
        public void CreationWillFailIfAllDepenciesAreMissingAndInjectAttributeIsApplied()
        {
            using ( IKernel kernel = new StandardKernel() )
            {
                kernel.Bind<NinjaBarracks>().ToSelf();

                Assert.Throws<ActivationException>( () => kernel.Get<NinjaBarracks>() );

                kernel.Bind<IWeapon>().To<Sword>();
                Assert.Throws<ActivationException>( () => kernel.Get<NinjaBarracks>() );
                kernel.Unbind<IWeapon>();

                kernel.Bind<IWarrior>().To<Samurai>();
                Assert.Throws<ActivationException>( () => kernel.Get<NinjaBarracks>() );
                kernel.Unbind<IWarrior>();
            }
        }
Ejemplo n.º 12
0
        private static IMediator BuildMediator()
        {
            var kernel = new StandardKernel();
            kernel.Components.Add<IBindingResolver, ContravariantBindingResolver>();
            kernel.Bind(scan => scan.FromAssemblyContaining<IMediator>().SelectAllClasses().BindDefaultInterface());
            kernel.Bind(scan => scan.FromAssemblyContaining<Ping>().SelectAllClasses().BindAllInterfaces());
            kernel.Bind<TextWriter>().ToConstant(Console.Out);

            var serviceLocator = new NinjectServiceLocator(kernel);
            var serviceLocatorProvider = new ServiceLocatorProvider(() => serviceLocator);
            kernel.Bind<ServiceLocatorProvider>().ToConstant(serviceLocatorProvider);

            var handlers = kernel.GetAll<INotificationHandler<Pinged>>();

            var mediator = serviceLocator.GetInstance<IMediator>();

            return mediator;
        }
Ejemplo n.º 13
0
        public void SpecificValueShouldBeUsedWhenSupplied()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind<Shield>().ToSelf().WithConstructorArgument("color", ShieldColor.Orange);

                var shield = kernel.Get<Shield>();
                shield.ShouldNotBeNull();
                shield.Color.ShouldBe(ShieldColor.Orange);
            }
        }
Ejemplo n.º 14
0
        public void DefaultValueShouldBeUsedWhenNoneSupplied()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind<Shield>().ToSelf();

                var shield = kernel.Get<Shield>();
                shield.ShouldNotBeNull();
                shield.Color.ShouldBe(ShieldColor.Red);
            }
        }
Ejemplo n.º 15
0
        public void InstancesCanBeCreated()
        {
            using (var kernel = new StandardKernel())
            {
                kernel.Bind<IConfig>().ToProvider<ConfigProvider>();

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

                instance.Should().NotBeNull();
            }
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            var kerner = new StandardKernel();
            //kerner.Bind<ICreditCard>().To<MasterCard>();
            kerner.Bind<ICreditCard>().To<Visa>();
            kerner.Rebind<ICreditCard>().To<MasterCard>();

            var shopper = kerner.Get<Shopper>();

            Console.WriteLine(shopper.Charge());
            Console.Read();
        }
Ejemplo n.º 17
0
        public void DefaultValuesAreEvaluatedForEachRequest()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind<Barracks>().ToConstructor(_ => new Barracks(new Ninja(new Sword())));

                var barracks1 = kernel.Get<Barracks>();
                var barracks2 = kernel.Get<Barracks>();

                barracks1.Warrior.Should().NotBeSameAs(barracks2.Warrior);
            }
        }
Ejemplo n.º 18
0
        public void DefaultCtorIsUsedWhenNoBindingAreAvailable()
        {
            using ( IKernel kernel = new StandardKernel() )
            {
                kernel.Bind<Barracks>().ToSelf();

                var barracks = kernel.Get<Barracks>();
                barracks.ShouldNotBeNull();
                barracks.Warrior.ShouldBeNull();
                barracks.Weapon.ShouldBeNull();
            }
        }
        public void DefaultCtorIsUsedWhenNoBindingAreAvailable()
        {
            using ( IKernel kernel = new StandardKernel() )
            {
                kernel.Bind<Barracks>().ToSelf();

                var barracks = kernel.Get<Barracks>();
                Assert.NotNull( barracks );
                Assert.Null( barracks.Warrior );
                Assert.Null( barracks.Weapon );
            }
        }
Ejemplo n.º 20
0
        public void ConstantsCanBePassedToToConstructor()
        {
            using (IKernel kernel = new StandardKernel())
            {
                var ninja = new Ninja(new Sword());
                kernel.Bind<Barracks>().ToConstructor(_ => new Barracks(ninja));

                var barracks1 = kernel.Get<Barracks>();
                var barracks2 = kernel.Get<Barracks>();

                barracks1.Warrior.Should().BeSameAs(barracks2.Warrior);
            }
        }
        public void CanBeBoundToPartiallyClosedGenericInterface()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind(
                    x => x.FromThisAssembly()
                          .Select(t => t == typeof(OpenGenericClassWithManyInterfaces<>))
                          .BindAllInterfaces());
                var instance = kernel.Get<IBaseOpenGenericInterface<double, int>>();

                instance.Should().BeAssignableTo<OpenGenericClassWithManyInterfaces<double>>();
            }
        }
        public void CanBeBoundToClosedGenericInterface()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind(
                    x => x.FromThisAssembly()
                          .SelectAllClasses().InNamespaceOf<ClassWithManyInterfaces>()
                          .BindAllInterfaces());
                var instance = kernel.Get<IClosedGenericInterface<int>>();

                instance.Should().BeAssignableTo<ClassWithManyInterfaces>();
            }
        }
        public void CanBeBoundToOpenGenericInterface()   
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind(
                    x => x.FromThisAssembly()
                          .SelectAllClasses().InNamespaceOf(typeof(OpenGenericClassWithManyInterfaces<>))
                          .BindAllInterfaces());
                var instance = kernel.Get<IOpenGenericInterface<double>>();

                instance.Should().BeAssignableTo<OpenGenericClassWithManyInterfaces<double>>();
            }
        }
        public void CanBeBoundToNormalBaseType()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind(
                    x => x.FromThisAssembly()
                          .SelectAllClasses().InNamespaceOf<ClassWithManyInterfaces>()
                          .BindSelection((ts, ti) => ti.Where(i => !i.IsInterface)));
                var instances = kernel.GetAll<object>();

                instances.Select(i => i.GetType()).Should().BeEquivalentTo(typeof(DefaultConvention), typeof(ClassWithManyInterfaces));
            }
        }
        public void TestNetworkMessageCanBeSerialized()
        {
            var kernel = new StandardKernel();
            kernel.Load<ProtogameNetworkModule>();
            kernel.Bind<INetworkMessage>().To<TestNetworkMessage>();

            var serializer = kernel.Get<INetworkMessageSerialization>();
            var message = new TestNetworkMessage
            {
                TestInteger = 5,
                TestString = "hello world"
            };
            serializer.Serialize(message);
        }
        public void CtorIsUsedWhenParameterIsSupplied()
        {
            using(IKernel kernel = new StandardKernel())
            {
                kernel.Bind<Barracks>().ToSelf();
                var constructorArgument = new ConstructorArgument("warrior", new Samurai(new Sword()));
                var barracks = kernel.Get<Barracks>(constructorArgument);

                Assert.NotNull(barracks);
                Assert.NotNull(barracks.Warrior);
                Assert.NotNull(barracks.Warrior.Weapon);
                Assert.Null(barracks.Weapon);
            }
        }
        public void AssemblyCanBeSpecifiedUsingAssemblyFileName()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind(
                    x => x.From("TestPlugin.dll")
                          .SelectAllTypes()
                          .BindDefaultInterface());
                var instance = kernel.Get<IDefaultConvention>();

                instance.Should().NotBeNull();
                instance.Name.Should().Be("DefaultConventionFromPlugin");
            }
        }
        public void AssemblyCanBeSpecifiedUsingThisAssembly()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind(
                    x => x.FromThisAssembly()
                          .SelectAllTypes()
                          .BindDefaultInterface());
                var instance = kernel.Get<IDefaultConvention>();

                instance.Should().NotBeNull();
                instance.Should().BeOfType<DefaultConvention>();
            }
        }
        public void CanBeBoundToOpenGenericInterfaceOfPartiallyClosedBaseClass()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind(
                    x => x.FromThisAssembly()
                          .SelectAllClasses().InNamespaceOf(typeof(OpenGenericClassWithManyInterfaces<>))
                          .BindAllInterfaces());
                var instances = kernel.GetAll<IBaseOpenGenericInterface1<double>>();

                instances.Select(i => i.GetType()).Should().BeEquivalentTo(
                    typeof(OpenGenericClassWithManyInterfaces<double>),
                    typeof(GenericBaseClassWithManyInterfaces<double>));
            }
        }
        public void AssemblyCanBeSpecifiedUsingFrom()
        {
            using (IKernel kernel = new StandardKernel())
            {
                kernel.Bind(
                    x => x.From(Assembly.GetExecutingAssembly())
                          .IncludingNonePublicTypes()
                          .SelectAllTypes()
                          .BindAllInterfaces());
                var instance = kernel.Get<IInternalInterface>();

                instance.Should().NotBeNull();
                instance.Should().BeOfType<InternalType>();
            }
        }
Ejemplo n.º 31
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);
        }
Ejemplo n.º 32
0
        public NinjectResolver GetResolver()
        {
            var kernel = new StandardKernel();

            kernel.Bind <IBooksRepository>().To <InMemoryBooksRepository>().InSingletonScope();
            kernel.Bind <IAuthorsRepository>().To <InMemoryAuthosRepository>().InSingletonScope();
            kernel.Bind <IFilesRepository>().To <SimpleFileRepository>().InSingletonScope();
            kernel.Bind <IUserSettingsRepository>().To <InMemorySettingsRepository>().InSingletonScope();
            kernel.Bind <BooksService>().ToSelf().InTransientScope();
            kernel.Bind <UserService>().ToSelf().InTransientScope();
            //kernel.Bind<BooksController>().ToSelf().InTransientScope();

            var ninjectResolver = new NinjectResolver(kernel);

            return(ninjectResolver);
        }
Ejemplo n.º 33
0
        public override void Init()
        {
            base.Init();
            // Dependency Injection
            IKernel diKernel = new StandardKernel();

            diKernel.Bind <IBlogRepository>().To <BlogRepository>();
            diKernel.Bind <IMenuRepository>().To <MenuRepository>();
            diKernel.Bind <ISliderRepository>().To <SliderRepository>();
            diKernel.Bind <IUserRepository>().To <UserRepository>();
            diKernel.Bind <ILanguageRepository>().To <LanguageRepository>();
            diKernel.Bind <IPageRepository>().To <PageRepository>();
            diKernel.Inject(Membership.Provider);
            DependencyResolver.SetResolver(new WebsiteDependencyResolver(diKernel));
            _LanguageRepository = (ILanguageRepository)DependencyResolver.Current.GetService(typeof(ILanguageRepository));
        }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            var hostings = new DirectoryInfo(Environment.CurrentDirectory).GetSubDirectory("hostings");

            var kernel = new StandardKernel();

            kernel.Bind(scaner =>
            {
                scaner
                .FromAssembliesInPath(hostings.FullName)
                .Select(t => typeof(IHostingManager).IsAssignableFrom(t))
                .BindAllInterfaces();
            });
            kernel.Bind(scaner =>
            {
                scaner
                .FromAssembliesInPath(hostings.FullName)
                .Select(t => typeof(IMultiHostingManager).IsAssignableFrom(t))
                .BindAllInterfaces();
            });

            kernel.Bind <ServicesCollection>().ToSelf().InSingletonScope();
            kernel.Bind <TopologyConfigurator>().ToSelf().InSingletonScope();
            kernel.Bind <IHostingProvider>().ToMethod(c => c.Kernel.Get <TopologyConfigurator>()).InSingletonScope();
            kernel.Bind <HostingTreeBuilder>().ToSelf().InSingletonScope();
            kernel.Bind <CredentialsFormatter>().ToSelf().InSingletonScope();
            kernel.Bind <FileHostingClient>().ToSelf().InSingletonScope();

            var configurator = kernel.Get <TopologyConfigurator>();
            var client       = kernel.Get <FileHostingClient>();

            var commands = new CommandsCollection();

            commands.AddCommandsProvider(configurator);
            commands.AddCommandsProvider(client);
            ConsoleApplication.Run(commands);
        }
Ejemplo n.º 35
0
    static void Main()
    {
        #region ContainerConfiguration
        BusConfiguration configuration = new BusConfiguration();
        configuration.EndpointName("Samples.Ninject");

        StandardKernel 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 (IStartableBus bus = Bus.Create(configuration))
        {
            bus.Start();
            bus.SendLocal(new MyMessage());
            Console.WriteLine("Press any key to exit");
            Console.Read();
        }
    }
Ejemplo n.º 36
0
        private static IKernel CreateKernel(params INinjectModule[] modules)
        {
            var kernel = new StandardKernel();

            try
            {
                kernel.Bind <Func <IKernel> >().ToMethod(ctx => () => new Bootstrapper().Kernel);
                //kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
                if (modules != null)
                {
                    kernel.Load(modules); // load modules
                }
                var config = StartupConfig.Config;
                config.DependencyResolver = new NinjectDependencyResolver(kernel);
                return(kernel);
            }
            catch (Exception ex)
            {
                kernel.Dispose();
                throw;
            }
        }
Ejemplo n.º 37
0
            public void should_handle_state_changes()
            {
                const string producerConfig =
                    @"<endpoints>
                        <endpoint name=""producer"" connectionString=""amqp://localhost/integration"" lifecycleHandler=""ProducerHandler"">
                            <outgoing>
                                <route key=""a"" label=""msg.a"" />
                            </outgoing>
                        </endpoint>
                    </endpoints>";

                var handler = new Mock <IBusLifecycleHandler>();

                IKernel kernel = new StandardKernel();

                kernel.Bind <IBusLifecycleHandler>().
                ToConstant(handler.Object).
                Named("ProducerHandler");

                DependencyResolverFunc dependencyResolver = (name, type) => kernel.Get(type, name);

                IBus producer = this.StartBus(
                    "producer",
                    cfg =>
                {
                    var section = new XmlEndpointsSection(producerConfig);
                    new AppConfigConfigurator(section, dependencyResolver).Configure("producer", cfg);
                });

                handler.Verify(h => h.OnStarting(It.IsAny <IBus>(), It.IsAny <EventArgs>()), Times.Once);
                handler.Verify(h => h.OnStarted(It.IsAny <IBus>(), It.IsAny <EventArgs>()), Times.Once);
                handler.Verify(h => h.OnStopping(It.IsAny <IBus>(), It.IsAny <EventArgs>()), Times.Never);
                handler.Verify(h => h.OnStopped(It.IsAny <IBus>(), It.IsAny <EventArgs>()), Times.Never);

                producer.Stop();

                handler.Verify(h => h.OnStopping(It.IsAny <IBus>(), It.IsAny <EventArgs>()), Times.Once);
                handler.Verify(h => h.OnStopped(It.IsAny <IBus>(), It.IsAny <EventArgs>()), Times.Once);
            }
Ejemplo n.º 38
0
        public void ShouldFindCandidateViewInRegion()
        {
            IKernel kernel = new StandardKernel();

            kernel.Bind <object, MockView>().To <MockView>().Named("MockView");

            ConfigureMockServiceLocator(kernel);

            IRegion testRegion = new Region();

            var view = new MockView();

            testRegion.Add(view);
            testRegion.Deactivate(view);

            testRegion.RequestNavigate("MockView");

            Assert.True(testRegion.Views.Contains(view));
            Assert.True(testRegion.Views.Count() == 1);
            Assert.True(testRegion.ActiveViews.Count() == 1);
            Assert.True(testRegion.ActiveViews.Contains(view));
        }
Ejemplo n.º 39
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));

        // get the interface implementation
        IValueCalculator calcImpl = ninjectKernel.Get <IValueCalculator>();
        // create the instance of ShoppingCart and inject the dependency
        //ShoppingCart cart = new ShoppingCart(new LinqValueCalculator());
        ShoppingCart cart = new ShoppingCart(calcImpl);

        // perform the calculation and write out the result
        Console.WriteLine("Total: {0:c}", cart.CalculateStockValue());
    }
Ejemplo n.º 40
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());

            // A real code generator would make the source of definitions dynamic
            var idlFiles = Directory.GetFiles("Idl", "*.idl.json").ToList();
            var idl      = idlFiles.Select(path => JObject.Parse(File.ReadAllText(path)));

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

            generator.GenerateCode(idl);
        }
Ejemplo n.º 41
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 <IWorktaskRepository>().To <EFWorktaskRepository>();
                kernel.Bind <IAccountRepository>().To <EFAccountRepository>();
                kernel.Bind <IDepartmentRepository>().To <EFDepartmentRepository>();
                kernel.Bind <ICategoryRepository>().To <EFCategoryRepository>();
                kernel.Bind <IBoardRepository>().To <EFBoardRepository>();
                kernel.Bind <IWorkflowRepository>().To <EFWorkflowRepository>();

                RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Ejemplo n.º 42
0
        /// <summary>
        ///     Creates the kernel.
        /// </summary>
        /// <returns>the newly created kernel.</returns>
        private static StandardKernel CreateKernel()
        {
            var kernel = new StandardKernel();

            kernel.Load(Assembly.GetExecutingAssembly());

            kernel.Bind(typeof(ConnectionFactory)).To(typeof(ConnectionFactory));
            kernel.Bind(typeof(MongoDbConnection)).ToMethod(x => x.Kernel.Get <ConnectionFactory>().GetConnection());

            kernel.Bind(typeof(IMongoDataBaseWithUser)).To(typeof(Database));
            kernel.Bind(typeof(IUppyDataManagersFactory)).To(typeof(UppyDataMangersFactory));
            kernel.Bind(typeof(IDataManagersFactory)).To(typeof(UppyDataMangersFactory));

            kernel.Bind(typeof(ITicketAutUser)).ToMethod(x => new TicketAutUser("web", "bad ticket"));

            return(kernel);
        }
Ejemplo n.º 43
0
        static MenuForm()
        {
            var contein = new StandardKernel();

            contein.Bind <HeightMapGenerator>()
            .To <BilinearValueInterpolationGenerator>()
            .Named("BilinearValueInterpolationGenerator");
            contein.Bind <HeightMapGenerator>()
            .To <NonlinearValueInterpolationGenerator>()
            .Named("NonlinearValueInterpolationGenerator");
            contein.Bind <HeightMapGenerator>()
            .To <CosineValueInterpolationGenerator>()
            .Named("CosineValueInterpolationGenerator");
            contein.Bind <HeightMapGenerator>()
            .To <PerlinGradientInterpolationGenerator>()
            .Named("PerlinGradientInterpolationGenerator");
            contein.Bind <HeightMapGenerator>()
            .To <HillGenerator>()
            .Named("HillGenerator");
            contein.Bind <HeightMapGenerator>()
            .To <DiamondSquareGenerator>()
            .Named("DiamondSquareGenerator");
            contein.Bind <IGeneratorFactory>()
            .ToFactory(() => new UseFirstArgumentAsNameInstanceProvider());
            container = contein;
            Type ourtype = typeof(HeightMapGenerator);
            var  d       = Assembly
                           .GetAssembly(ourtype)
                           .GetTypes()
                           .Where(type => ourtype.IsAssignableFrom(type) && !type.IsAbstract)
                           .ToDictionary(t => t.Name, t => {
                var parameters =
                    t.GetProperties()
                    .Where(p => !p.IsPrivate())
                    .Select(p => p.Name)
                    .ToList();
                return(parameters);
            });

            generatorsNamesParameters = d;
        }
Ejemplo n.º 44
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 <IRestaurantStore>().To <RestaurantStore>();
                kernel.Bind <IMenuStore>().To <MenuStore>();
                kernel.Bind <IItemStore>().To <ItemStore>();
                kernel.Bind <IHoursStore>().To <HoursStore>();
                kernel.Bind <ILocationStore>().To <LocationStore>();
                kernel.Bind <IGeocoder>().To <Geocoder>();

                RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Ejemplo n.º 45
0
        protected override IKernel CreateKernel()
        {
            var kernel = new StandardKernel();

            string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            kernel.Bind <IParkDAL>().To <ParkSqlDAL>().WithConstructorArgument("connectionString", connectionString);
            kernel.Bind <ITrailDAL>().To <TrailSqlDAL>().WithConstructorArgument("connectionString", connectionString);
            kernel.Bind <IPanoramicDAL>().To <PanoramicSqlDAL>().WithConstructorArgument("connectionString", connectionString);
            kernel.Bind <ILastSeenImagesDAL>().To <LastSeenImagesSqlDAL>().WithConstructorArgument("connectionString", connectionString);
            kernel.Bind <ILastSeenVideosDAL>().To <LastSeenVideosSqlDAL>().WithConstructorArgument("connectionString", connectionString);
            kernel.Bind <IAdminNewHotspotDAL>().To <AdminNewHotspotSqlDAL>().WithConstructorArgument("connectionString", connectionString);

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

            return(kernel);
        }
        protected override IKernel CreateKernel()
        {
            var kernel = new StandardKernel();

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

            kernel.Bind <IReadOnlyRepository>().To <ReadOnlyRepository>();
            kernel.Bind <IWriteOnlyRepository>().To <WriteOnlyRepository>();
            kernel.Bind <ISession>().ToMethod(x => SessionFactory.GetCurrentSession());
            kernel.Bind <IMappingEngine>().ToConstant(Mapper.Engine);
            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

            return(kernel);
        }
        public static StandardKernel Configure()
        {
            var kernel = new StandardKernel();

            // register the different consumers and classes
            kernel.Bind <IRepositoryManager>().To(typeof(RepositoryManager));
            kernel.Bind <IRepositoryConnectionFactory>().To(typeof(RepositoryConnectionFactory));
            kernel.Bind <IRepositoryDataAccess>().To(typeof(RepositoryDataAccess));
            kernel.Bind <IPackageValidator>().To(typeof(PackageValidator));
            kernel.Bind <IMetadataDataAccess>().To(typeof(MetadataDataAccess));
            kernel.Bind <IPackageHandler>().To(typeof(PackageHandler));
            kernel.Bind <IParameterHelper>().To(typeof(ParameterHelper));

            // just register all the consumers using Ninject.Extensions.Conventions
            kernel.Bind(x =>
            {
                x.FromThisAssembly()
                .SelectAllClasses()
                .InheritedFrom <IConsumer>()
                .BindToSelf();
            });

            return(kernel);
        }
Ejemplo n.º 48
0
        public void SetUp()
        {
            kernel = new StandardKernel();
            Kernel.RegisterCoreBindings(kernel);
            kernel.Bind <IFileSystemDirectory>().ToConstant(new TestFileSystemDirectory("root")).WhenTargetHas
            <SuiteRootAttribute>();
            kernel.Bind <IFileSystemDirectory>().ToConstant(new TestFileSystemDirectory("target")).WhenTargetHas <TargetRootAttribute>();
            kernel.Bind <Lazy <IFileSystemDirectory> >().ToConstant(new Lazy <IFileSystemDirectory>(() => new TestFileSystemDirectory("cache"))).WhenTargetHas <CacheRootAttribute>();
            kernel.Bind <IUserOutput>().To <TestUserOutput>();

            parameters = new Mock <IParameters>();
            parameters.SetupGet(p => p.Goal).Returns("debug");
            kernel.Bind <IParameters>().ToConstant(parameters.Object);
            TestSetup.EnsureFactoryExtensionLoaded(kernel);

            kernel.Rebind <ISuiteFactory>().To <DefaultSuiteFactory>().InTransientScope();

            fsAccess = new Mock <IFileSystemRepositoryAccess>().Object;
            kernel.Bind <IFileSystemRepositoryAccess>().ToConstant(fsAccess);
            kernel.Bind <IYamlProjectParametersLoader>().To <YamlRepositoryPatternCollectionLoader>();
        }
Ejemplo n.º 49
0
        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();
        }
Ejemplo n.º 50
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;
            }
        }
Ejemplo n.º 51
0
        private static StandardKernel CreateKernel()
        {
            var kernel = new StandardKernel(new UnitOfWorkModule());

            //Service register
            kernel.Bind <IUserService>().To <UserService>();
            kernel.Bind <IDispatcherService>().To <DispatcherService>();
            kernel.Bind <IDriverService>().To <DriverService>();
            kernel.Bind <IAutoService>().To <AutoService>();
            kernel.Bind <IFlightService>().To <FlightService>();
            kernel.Bind <IFlightRequestService>().To <FlightRequestService>();
            kernel.Bind <ILoggerService>().To <LogService>();

            //Filter register
            kernel.BindFilter <ExceptionLoggerFilter>(FilterScope.Controller, 0)
            .WhenControllerHas <ExceptionLoggerAttribute>();
            kernel.BindFilter <ActionLoggerFilter>(FilterScope.Controller, 0)
            .WhenControllerHas <ActionLoggerAttribute>();

            return(kernel);
        }
        public void IfMissingRequiredFieldsItReturnsBadRequest()
        {
            // Arrange
            var badCar = new Car
            {
                Name = "Empty"
            };

            var service = new Mock <ICarService>();

            service.Setup(m => m.Create(It.IsAny <Data.Models.Car>()))
            .ReturnsAsync(TestHelpers.Fixture.Create <Data.Models.Car>());

            // Bind our mock with Ninject
            var kernel = new StandardKernel();

            kernel.Bind <ICarService>().ToConstant(service.Object);
            var container = new ExampleContainer(new Uri(BaseAddress));

            using (WebApp.Start(BaseAddress, app => TestHelpers.ConfigureWebApi(app, kernel)))
            {
                // Act
                try
                {
                    container.AddToCars(badCar);
                    container.SaveChanges();
                }
                catch (DataServiceRequestException exception)
                {
                    var inner = exception.InnerException as DataServiceClientException;
                    Assert.IsNotNull(inner);
                    Assert.AreEqual((int)HttpStatusCode.BadRequest, inner.StatusCode);
                    return;
                }
                // Assert
                Assert.Fail("Exception not caught.");
            }
        }
Ejemplo n.º 53
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            ILog logger = LogManager.GetLogger(typeof(Program));

            try
            {
                IKernel kernel = new StandardKernel();
                kernel.Bind <IUserRepository>().To <UserRepository>();

                IUserRepository userRepo = kernel.Get <IUserRepository>();

                foreach (var user in userRepo.GetAllUsers())
                {
                    Console.WriteLine("{0}:\t {1} {2}", user.Id, user.FirstName, user.Name);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            Console.ReadLine();
        }
Ejemplo n.º 54
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>();

                var progressConfiguration = new ProgressConfiguration();

                var properties = RunTimeProperties.GetStaticProperties();
                if (properties.SessionModel == SessionModelConstants.SessionManaged || progressConfiguration.InforProgressOwnsConnection)
                {
                    // Get a new instance of the Connection object each time
                    kernel.Bind <Connection>()
                    .To <Connection>()
                    .WithConstructorArgument(RunTimeProperties.GetStaticProperties());
                }
                else
                {
                    // This registration causes the Connection to act as a Pool and stays around for the lifetime of the application
                    kernel.Bind <Connection>()
                    .To <Connection>()
                    .InSingletonScope()
                    .WithConstructorArgument(RunTimeProperties.GetStaticProperties());
                }

                kernel.Bind(scanner => scanner.FromAssembliesMatching("General.Business.dll")
                            .SelectAllClasses()
                            .InheritedFrom <IService>().BindDefaultInterfaces());

                kernel.Bind(scanner => scanner.FromAssembliesMatching("Infor.Sxe.*.Data.dll")
                            .SelectAllClasses()
                            .InheritedFrom <IRepository>().BindDefaultInterfaces());

                RegisterServices(kernel);
                return(kernel);
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
Ejemplo n.º 55
0
Archivo: Program.cs Proyecto: akulin/di
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var container = new StandardKernel();

            container.Bind(kernel => kernel
                           .FromThisAssembly()
                           .SelectAllClasses()
                           .InheritedFrom <IUiAction>()
                           .BindAllInterfaces());

            container.Bind <Palette>().ToConstant(new Palette())
            .InSingletonScope();
            container.Bind <IImageHolder, PictureBoxImageHolder>()
            .To <PictureBoxImageHolder>()
            .InSingletonScope();

            container.Bind <IObjectSerializer>().To <XmlObjectSerializer>()
            .WhenInjectedInto <SettingsManager>();
            container.Bind <IBlobStorage>().To <FileBlobStorage>()
            .WhenInjectedInto <SettingsManager>();

            container.Bind <IImageDirectoryProvider, AppSettings>()
            .ToMethod(context => context.Kernel.Get <SettingsManager>().Load())
            .InSingletonScope();
            container.Bind <ImageSettings>()
            .ToMethod(context => context.Kernel.Get <AppSettings>().ImageSettings);

            try
            {
                var form = container.Get <MainForm>();
                Application.Run(form);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Ejemplo n.º 56
0
        public static void Register(StandardKernel kernel)
        {
            Kernel = kernel;

            var appSettings = new AppSettings();

            appSettings.Initialize();
            Kernel.Bind <IAppSettings>().ToConstant(appSettings).InSingletonScope();

            if (appSettings.StorageType == StorageType.Json)
            {
                Bind <IRepository, JsonRepository>();
            }
            if (appSettings.StorageType == StorageType.Sqlite)
            {
                Bind <IRepository, SqliteRepository>();
            }

            BindToSelf <DeliveryFactory>();
            BindToSelf <DeliveryService>();
            Bind <IExpirationPolicy, ExpirationPolicy>();
            Bind <IDeliveryPolicy, RandomDeliveryPolicy>();
        }
Ejemplo n.º 57
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 });
        }
Ejemplo n.º 58
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();
        }
Ejemplo n.º 59
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();
            }
        }
Ejemplo n.º 60
0
        public Launcher(params string[] args)
        {
            mConfig = new LauncherConfig(args);

            if (mConfig.InitKinect && !GlobalConditions.Init())
            {
                Logger.Fatal("Unable to initialise Kinect. Exiting.");
                return;
            }

            var settings = new NinjectSettings {
                LoadExtensions = false
            };
            IKernel k = new StandardKernel(settings, new XmlExtensionModule());

            if (mConfig.BindingsFile == null)
            {
                Logger.Warn("Unable to launch. No bindings file specified.");
                return;
            }
            try {
                k.Load(mConfig.BindingsFile);
            } catch (Exception e) {
                Logger.Warn("Unable to launch. Problem loading bindings. " + e.Message);
            }
            if (k.TryGet <IMediaPlayer>() == null)
            {
                k.Bind <IMediaPlayer>().To <DummyPlayer>().InSingletonScope();
            }

            try {
                mCore = k.Get <Core>();
            } catch (Exception e) {
                Logger.Warn("Unable to launch. Problem instantiating coordinator. " + (e.InnerException != null ? e.InnerException.Message :e.Message));
                //Logger.Debug("", e);
            }
        }