The standard implementation of a kernel.
Inheritance: KernelBase
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var documentStore = new EmbeddableDocumentStore
                {
                    UseEmbeddedHttpServer = true,
                    DataDirectory = "App_Data",
                    Configuration =
                        {
                            Port = 12345,
                        },
                    Conventions =
                        {
                            CustomizeJsonSerializer = MvcApplication.SetupSerializer
                        }
                };
            documentStore.Initialize();
            var manager = new SubscriptionManager(documentStore);

            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            kernel.Bind<IDocumentStore>()
                  .ToMethod(context => documentStore)
                  .InSingletonScope();
            RegisterServices(kernel);
            kernel.Bind<SubscriptionManager>().ToMethod(context => manager).InSingletonScope();
            return kernel;
        }
        public void It_should_resolve_binding_which_matches_all_constraints()
        {
            const string Name = "AnyName";

            var kernel = new StandardKernel();

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

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

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

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

            kernel
                .Get<IFactoryWithMultipleConstraints>()
                .Create(Name)
                .Should().BeSameAs(matchingAllConstraintsInstance);
        }
Example #3
0
        public void Should_not_throw_exception_when_loading_multiple_inline_modules()
        {
            IKernel kernel = new StandardKernel();

            kernel.Bind<IService>().To<ServiceImpl>();
            kernel.Bind<IService2>().To<Service2Impl>();
        }
Example #4
0
    static void Main()
    {
        Console.Title = "Samples.Ninject";
        Configure.Serialization.Json();

        #region ContainerConfiguration

        Configure configure = Configure.With();
        configure.Log4Net();
        configure.DefineEndpointName("Samples.Ninject");
        StandardKernel kernel = new StandardKernel();
        kernel.Bind<MyService>().ToConstant(new MyService());
        configure.NinjectBuilder(kernel);

        #endregion

        configure.InMemorySagaPersister();
        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();
        configure.UseTransport<Msmq>();
        using (IStartableBus startableBus = configure.UnicastBus().CreateBus())
        {
            IBus bus = startableBus.Start(() => configure.ForInstallationOn<Windows>().Install());
            bus.SendLocal(new MyMessage());

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Example #5
0
        private static void Main()
        {
            XmlConfigurator.Configure(new FileInfo("patientOrderService.log4net.xml"));

            HostFactory.Run(
                c =>
                    {
                        c.SetServiceName("SampleSOAPatientOrderService");
                        c.SetDisplayName("Sample SOA Patient Order Service");
                        c.SetDescription("A sample SOA service for handling Patient Orders.");

                        c.RunAsNetworkService();

                        StandardKernel kernel = new StandardKernel();
                        PatientOrderServiceRegistry module = new PatientOrderServiceRegistry();
                        kernel.Load(module);

                        c.Service<PatientOrderService>(
                            s =>
                                {
                                    s.ConstructUsing(builder => kernel.Get<PatientOrderService>());
                                    s.WhenStarted(o => o.Start());
                                    s.WhenStopped(o => o.Stop());
                                });
                    });
        }
 public void Init()
 {
     var container = new StandardKernel();
     container.Bind<ISessionRepository>().ToConstant(MoqSessionRepositoryFactory.GetSessionRepositoryMock());
     _sessionRepository = container.Get<ISessionRepository>();
     _sessionRepository.Clear();
 }
Example #7
0
        public void IsCallingMethodInfoErrorLogger1()
        {
            Mock <ILogger> mockNlog  = new Mock <ILogger>();
            string         password  = "******";
            string         nameFrom  = "Andrey";
            string         emailFrom = "*****@*****.**";
            string         emailTo   = "*****@*****.**";
            string         header    = "Hi!";
            string         message   = "This was a yours message...";
            var            kernel    = new Ninject.StandardKernel();

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

            kernel.Bind <ILogger>().To <ConsoleLogger>();
            ILogger logger = kernel.Get <ILogger>();
        }
        static void Main(string[] args)
        {
            NinjectModule module = new DepInjModule();
            IKernel kernel = new StandardKernel(module);

            // Get object from DI container.
            //
            var logger = kernel.Get<ILogger>();

            var webSite = new WebSite(url);

            while (true)
            {
                try
                {
                    if (webSite.IsAvailable())
                        logger.Log(String.Format("{0} - Web site works", DateTime.Now));
                    else
                        logger.Log(String.Format("{0} - Web site status code isn't ok", DateTime.Now));
                }
                catch (Exception e)
                {
                    logger.Log(String.Format("{0} - {1}", DateTime.Now, e.Message));
                }

                Thread.Sleep(1000);
            }
        }
Example #10
0
 public object Ninject()
 {
     using (var kernel = new Ninject.StandardKernel())
     {
         return(kernel.Get <T>());
     }
 }
Example #11
0
 public void ShouldBeAbleToGetBusinessServiceFromNinject()
 {
     BusinessService actual;
     var kernel = new StandardKernel(new CoreModule());
     actual = kernel.Get<BusinessService>();
     Assert.IsNotNull(actual);
 }
        static void Main(string[] args)
        {           
            IKernel kernel = new StandardKernel();
            kernel.Bind<IBookRepository>().To<XmlFileRepository>().WithConstructorArgument(@"../../books.xml");
            kernel.Bind<ILogger>().To<Logger>();            
            kernel.Bind<IXmlExporter>().To<LinqToXmlExporter>();
            kernel.Bind<IBookListService>().To<BookListService>();
            IBookList list = kernel.Get<BookList>();

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

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

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

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

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

            Console.ReadLine();
        }
Example #13
0
        private static IRestClient GetRestClient()
        {
            IKernel kernel = new StandardKernel();
            kernel.Load(Assembly.GetExecutingAssembly());

            return kernel.Get<IRestClient>();
        }
Example #14
0
        public void _お金の排出依頼を処理する()
        {
            var parameters = new _コマンドパーサに渡すTestFixture().InsMoneyParams
                             .Select(p => p.Expected)
                             .Cast <MoneyInsertionParseResult>()
            ;

            var repo = new Ninject.StandardKernel()
                       .BindPurchaseContext()
                       .BindRunnerRepository()
                       .Get <IRunnerRepository>()
            ;

            Action runner;

            foreach (var parameter in parameters)
            {
                runner = repo.FindRunner(parameter, null);
                runner();
            }

            Assert.That(repo.PurchaseContext.ReceivedTotal, Is.GreaterThan(0));

            runner = repo.FindRunner(new MoneyEjectParseResult(), null);
            runner();

            Assert.That(repo.PurchaseContext.ReceivedTotal, Is.EqualTo(0));
        }
Example #15
0
        public void _ヘルプ表示依頼を処理する_コマンド指定()
        {
            var repo = new Ninject.StandardKernel()
                       .BindPurchaseContext()
                       .BindRunnerRepository()
                       .Get <IRunnerRepository>()
            ;

            var result = new HelpParseResult {
                Command = "ins"
            };
            var content = ConsoleAppHelper.ListHelpContents()
                          .Where(c => c.Command == result.Command).FirstOrDefault();

            var it = (new string[] { content.Usage, content.Description }).GetEnumerator();

            var runner = repo.FindRunner(result, (message) => {
                Assert.That(it.MoveNext(), Is.True);
                Assert.That(message, Is.Not.Null.And.Not.Empty);
                Assert.That(message, Is.EqualTo(it.Current));
            });

            runner();

            Assert.That(it.MoveNext(), Is.False);
        }
Example #16
0
        public void _投入合計金額表示を処理する_受け付けない金種を投入した場合()
        {
            var repo = new Ninject.StandardKernel()
                       .BindPurchaseContext()
                       .BindRunnerRepository()
                       .Get <IRunnerRepository>()
            ;

            Action runner;
            var    fixtures = new _コマンドパーサに渡すTestFixture().InvalidInsMoneyParams;

            foreach (var param in fixtures.Select(f => f.Expected))
            {
                runner = repo.FindRunner(param, null);
                runner();

                var passed = false;
                runner = repo.FindRunner(new ShowAmountParseResult(), (message) => {
                    Assert.That(message, Is.EqualTo("Not received."));
                    passed = true;
                });
                runner();

                Assert.That(repo.PurchaseContext.ReceivedTotal, Is.EqualTo(0));
                Assert.That(passed, Is.True);
            }
        }
Example #17
0
        public void _陳列された商品の表示依頼を処理する_未入金の場合()
        {
            var repo = new Ninject.StandardKernel()
                       .BindPurchaseContextContainingSoldout()
                       .BindRunnerRepository()
                       .Get <IRunnerRepository>()
            ;

            Assert.That(repo.PurchaseContext.ReceivedTotal, Is.EqualTo(0));

            var expected = new string[] {
                "       # Name                     Price",
                "-----+--+------------------------+------",
                " [ ]   1 Item0...................   300",
                " [ ]   2 Item1...................  1200",
                " [-]   3 Item2...................   900",
                " [ ]   4 Item3...................   600"
            };

            var it = expected.GetEnumerator();

            var runner = repo.FindRunner(new ShowItemParseResult(), (message) => {
                Assert.That(it.MoveNext(), Is.True);
                Assert.That(message, Is.EqualTo(it.Current));
            });

            runner();

            Assert.That(repo.PurchaseContext.ReceivedTotal, Is.EqualTo(0));
            Assert.That(it.MoveNext(), Is.False);
        }
Example #18
0
        public void _パースされた投入金額を処理する_連続投入()
        {
            var parameters = new _コマンドパーサに渡すTestFixture().InsMoneyParams
                             .Select(p => p.Expected)
                             .Cast <MoneyInsertionParseResult>();

            var repo = new Ninject.StandardKernel()
                       .BindPurchaseContext()
                       .BindRunnerRepository()
                       .Get <IRunnerRepository>()
            ;

            foreach (var parameter in parameters)
            {
                var runner = repo.FindRunner(parameter, null);

                runner();
            }

            var totalAmount = parameters
                              .Sum(r => (r.Money.Value() * r.Count))
            ;

            Assert.That(repo.PurchaseContext.ReceivedTotal, Is.EqualTo(totalAmount));
        }
        //
        // GET: /Management/
        public ActionResult Index()
        {
            IKernel kernel = new StandardKernel(new DataModelCreator());
            var users = kernel.Get<IRepository<User>>().GetAll().Where(u => u.Id != WebSecurity.CurrentUserId);

            return View(users);
        }
Example #20
0
        static void Main()
        {
            Log4NetLogger.Use("cashier.log4net.xml");

            HostFactory.Run(c =>
                {
                    c.SetServiceName("StarbucksCashier");
                    c.SetDisplayName("Starbucks Cashier");
                    c.SetDescription("a Mass Transit sample service for handling orders of coffee.");

                    c.RunAsLocalSystem();
                    c.DependsOnMsmq();

                    var kernel = new StandardKernel();
                    var module = new CashierRegistry();
                    kernel.Load(module);

                    DisplayStateMachine();

                    c.Service<CashierService>(s =>
                        {
                            s.ConstructUsing(builder => kernel.Get<CashierService>());
                            s.WhenStarted(o => o.Start());
                            s.WhenStopped(o => o.Stop());
                        });
                });
        }
Example #21
0
        public void IsCallingMethodInfoErrorLogger2()
        {
            Mock <ISmtpSender> mockSmtpSender = new Mock <ISmtpSender>();
            Mock <ILogger>     mockNlog       = new Mock <ILogger>();
            string             password       = "******";
            string             nameFrom       = "Andrey";
            string             emailFrom      = "*****@*****.**";
            string             emailTo        = "*****@*****.**";
            string             header         = "Hi!";
            string             message        = "This was a yours message...";
            string             directory      = "C:\\MailFolder";
            var kernel = new Ninject.StandardKernel();
            var s      = mockSmtpSender;

            kernel.Bind <IFileWatcher>().To <FileWatcher.FileWatcher>().Named("FileWatcher").WithConstructorArgument("directory", directory)
            .WithConstructorArgument("smtpSender", s.Object).WithConstructorArgument("logger", LogManager.GetCurrentClassLogger());
            new TaskFactory().StartNew(kernel.Get <IFileWatcher>().Run);
            Thread.Sleep(1000);
            if (File.Exists((directory + "\\r.txt")))
            {
                File.Delete((directory + "\\r.txt"));
            }
            using (File.Create(directory + "\\r.txt"))
                Thread.Sleep(1000);
            s.Verify(x => x.SendEmailAsync(It.IsAny <string>()), Times.Exactly(1));
        }
        public static Bitmap CreateEmbroidery(Bitmap image, int resolutionCoefficient, int cellsCount, Color[] palette, char[] symbols, Color symbolColor, GridType type)
        {
            IKernel kernel = new StandardKernel(new PropertiesModel());

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

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

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

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

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

            return result;
        }
Example #23
0
        public void InjectorTest()
        {
            Mock <ILogger> mockNlog  = new Mock <ILogger>();
            string         password  = "******";
            string         nameFrom  = "Andrey";
            string         emailFrom = "*****@*****.**";
            string         emailTo   = "*****@*****.**";
            string         header    = "Hi!";
            string         message   = "This was a yours message...";
            string         directory = "C:\\TestFolder";
            var            kernel    = new Ninject.StandardKernel();

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

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

            Assert.NotNull(smtpSender);
        }
Example #24
0
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var user = filterContext.HttpContext.Session.GetCurrentUser();

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

                        IUserManager userManager = ninjectKernel.Get <IUserManager>();
                        var          userService = userManager.Login(cookieUser.un, cookieUser.pwd, filterContext.HttpContext.Request.GetCurrentIP());
                        var          entry       = new UserSessionEntry
                        {
                            Name = userService.Name,
                            Uid  = userService.Uid
                        };
                        filterContext.HttpContext.Session.SetCurrentUser(entry);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
 public void nullFilePassedToSecurePutFileFails()
 {
     IKernel kernel = new StandardKernel(new BaseModule());
     kernel.Bind<IWebClientFactory>().To<StubWebClientFactory>().InSingletonScope();
     HttpResourceProvider provider = kernel.Get<HttpResourceProvider>();
     provider.securePutFile(new System.Uri("http://resourceServer.wherever"), null);
 }
Example #26
0
        private static void RegisterDependencyResolver()
        {
            var kernel = new StandardKernel();
            kernel.Bind<ICalendarService>().To<CalendarService>();

            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
        }
Example #27
0
        public ConnectInfoForm()
        {
            XmlConfigurator.Configure();

            var settings = new NinjectSettings()
            {
                LoadExtensions = false
            };

            this.mKernel = new StandardKernel(
                settings,
                new Log4NetModule(),
                new ReportServerRepositoryModule());

            //this.mKernel.Load<FuncModule>();

            this.mLoggerFactory = this.mKernel.Get<ILoggerFactory>();
            this.mFileSystem = this.mKernel.Get<IFileSystem>();
            this.mLogger = this.mLoggerFactory.GetCurrentClassLogger();

            InitializeComponent();

            this.LoadSettings();

            // Create the DebugForm and hide it if debug is False
            this.mDebugForm = new DebugForm();
            this.mDebugForm.Show();
            if (!this.mDebug)
                this.mDebugForm.Hide();
        }
Example #28
0
        public void update_value_object_with_direct_context()
        {
            UserTestData.PrepareUser(userId);

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

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

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

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

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

                // ups, we updated the object, but didn't reattach it to the new context!
                AssertThat.AreEqual(houseNo, user.Address.HouseNo);
            }
        }
 public BindingExtensionsTest()
 {
     this.eventAggregator = new Mock<IEventAggregator>();
     
     this.kernel = new StandardKernel(new NinjectSettings { LoadExtensions = false });
     this.kernel.Bind<IEventAggregator>().ToConstant(this.eventAggregator.Object);
 }
Example #30
0
		public static void Main (string[] args)
		{
		    var kernel = new StandardKernel();
		    Container = new Container(kernel);

		    Configure.With(Container)
                .UsingJsonStorage("JsonDB")
                .Initialize();

		    var commandCoordinator = ServiceLocator.Current.GetInstance<ICommandCoordinator>();

			var command = new CreatePerson(Guid.NewGuid(), "First", "Person");
			var result = commandCoordinator.Handle(command);
			if (!result.Success)
			{
				Console.WriteLine("Handling of command failed");
				Console.WriteLine("Exception : {0}\nStack Trace : {1}", result.Exception.Message, result.Exception.StackTrace);
			}

			var queries = Container.Get<IPersonView>();
			var persons = queries.GetAll();
			foreach (var person in persons)
			{
				Console.WriteLine("Person ({0}) - {1} {2}", person.Id, person.FirstName, person.LastName);
			}
		}
Example #31
0
        static void Main(string[] args)
        {
            DirEx direx;
            if (!ArgsBinder.TryParse(args, out direx))
            {
                throw new ArgsExeption(args);
            }

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

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

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

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

#if DEBUG
            Cmd.ReadKey();
#endif
        }
 private static StandardKernel CreateKernel()
 {
     var kernel = new StandardKernel();
     kernel.Load(Assembly.GetExecutingAssembly());
     RegisterMappings(kernel);
     return kernel;
 }
Example #33
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Setup Ninject Kernel and wire up services using convention based binding in Ninject 3.0
            var kernel = new StandardKernel();
            kernel.Bind(x => x
                .FromAssembliesMatching("*")
                .SelectAllClasses()
                .BindDefaultInterface());
            //Or bind each class using the following syntax:
            //kernel.Bind<IStupidLittleService>().To<StupidLittleService>().InRequestScope();

            //Setup DR for MVC Controllers
            NinjectDependencyResolver resolver = new NinjectDependencyResolver(kernel);
            DependencyResolver.SetResolver(resolver);

            //Setup DR for Web API Controllers
            NinjectWebApiDependencyResolver webApiDependencyResolver = new NinjectWebApiDependencyResolver(kernel);
            GlobalConfiguration.Configuration.DependencyResolver = webApiDependencyResolver;
        }
Example #34
0
        public void DoIt()
        {
            using (var kernel = new Ninject.StandardKernel())
            {
                kernel.Load <Nailhang.Mongodb.Module>();
                kernel.Rebind <Nailhang.Mongodb.MongoConnection>()
                .ToConstant(new MongoConnection
                {
                    ConnectionString = "mongodb://192.168.0.32",
                    DbName           = "nail_tests"
                });


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

                Assert.IsNotEmpty(ms.GetModules().ToArray());
                ms.DropModules("NOTREALNAMESPACE");
                Assert.IsNotEmpty(ms.GetModules().ToArray());
                ms.DropModules("");
                Assert.IsEmpty(ms.GetModules().ToArray());
            }
        }
        public void ItSavesNewCar()
        {
            // Arrange
            var newCar = new Car
                         {
                                 Name = "Hakosuka",
                                 Make = "Nissan",
                                 Model = "Skyline GTR",
                                 Year = 1996
                         };

            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 
                container.AddToCars( newCar );
                ChangeOperationResponse response = container.SaveChanges().Cast<ChangeOperationResponse>().First();
                var entityDescriptor = (EntityDescriptor) response.Descriptor;
                var actual =
                        (Car) entityDescriptor.Entity;

                // Assert 
                Assert.AreEqual( (int) HttpStatusCode.Created, response.StatusCode );
                service.Verify( m => m.Create( It.IsAny<Data.Models.Car>() ), Times.Once );
                Assert.IsNotNull( actual );
            }
        }
        public Comment GetComment(int id)
        {
            IKernel kernel = new StandardKernel(new DataModelCreator());
            var comment = kernel.Get<IRepository<Comment>>().GetById(id);

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

            RegisterServices(kernel);
            return kernel;
        }
 public ProductController()
 {
     // productService = ServiceLocator.GetProductService();
     IKernel ninjectKernel = new StandardKernel();
     ninjectKernel.Bind<IProductService>().To<ProductService>();
     serviceProduct = ninjectKernel.Get<IProductService>();
 }
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        internal static Func<IKernel> CreateKernel(bool useStaticInit)
        {
            return () =>
            {
                IKernel kernel;

                if (useStaticInit)
                    kernel = InitWithModules();
                else
                {
                    kernel = new StandardKernel();
                    LoadModules(kernel);
                }

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

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

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

                    throw;
                }
            };
        }
        public List<Comment> GetAllComments()
        {
            IKernel kernel = new StandardKernel(new DataModelCreator());
            var comments = kernel.Get<IRepository<Comment>>().GetAll();

            return comments.ToList();
        }
        public void ParsesCruiseControlServerCorrectly()
        {
            var kernel = new StandardKernel();

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

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

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

            var cruiseControlServer = parser.Parse(config) as CruiseControlServer;
            Assert.IsNotNull(cruiseControlServer);
            Assert.IsNotNull(cruiseControlServer.Config);
            var cruiseControlServerconfig = cruiseControlServer.Config;
            Assert.AreEqual("http://goserver.localdomain:8153/go/cctray.xml", cruiseControlServerconfig.URL);
            Assert.AreEqual("ci", cruiseControlServerconfig.Username);
            Assert.AreEqual("secret", cruiseControlServerconfig.Password);
            Assert.IsNotNull(cruiseControlServerconfig.Pipelines);
            Assert.AreEqual(2, cruiseControlServerconfig.Pipelines.Count());
        }
Example #42
0
 /// <summary>
 /// Creates the kernel that will manage your application.
 /// </summary>
 /// <returns>The created kernel.</returns>
 protected override IKernel CreateKernel()
 {
     var kernel = new StandardKernel();
     kernel.Bind<IHomeControllerModel>().To<HomeControllerModel>();
     kernel.Bind<ILog>().ToMethod(ctx => LogManager.GetLogger("xxx"));
     return kernel;
 }
Example #43
0
        private void Initialize()
        {
            if (_kernel != null) return;
            _kernel = new StandardKernel();
            _kernel.Bind<Func<Type, NotifyableEntity>>().ToMethod(context => t => context.Kernel.Get(t) as NotifyableEntity);
            _kernel.Bind<PhoneApplicationFrame>().ToConstant(new PhoneApplicationFrame());
            _kernel.Bind<INavigationService>().To<NavigationService>().InSingletonScope();
            _kernel.Bind<IStorage>().To<IsolatedStorage>().InSingletonScope();
            _kernel.Bind<ISerializer<byte[]>>().To<BinarySerializer>().InSingletonScope();
            _kernel.Bind<IDataContext>().To<DataContext>().InSingletonScope();
            _kernel.Bind<IGoogleMapsClient>().To<GoogleMapsClientMock>().InSingletonScope();
            _kernel.Bind<IConfigurationContext>().To<ConfigurationContext>().InSingletonScope();

            ApplicationContext.Initialize(_kernel);
            var place1 = ApplicationContext.Data.AddNewPlace(new Location
            {
                Latitude = 9.1540930,
                Longitude = -1.39166990
            });
            var place2 = ApplicationContext.Data.AddNewPlace(new Location
            {
                Latitude = 9.1540930,
                Longitude = -1.39166990
            });
            ApplicationContext.Data.GetRoute(null, null, default(TravelMode), default(RouteMethod), r =>
            {
                r.Result.ArrivalPlaceId = place1.Id;
                r.Result.DeparturePlaceId = place2.Id;
            });
            ApplicationContext.Data.ToolbarAlignment.Value = HorizontalAlignment.Left;
        }
Example #44
0
        public override void OnCreate()
        {
            var kernel = new Ninject.StandardKernel(new NinjectDemoModule());

            App.Container = kernel;

            base.OnCreate();
        }
Example #45
0
        public static void Init()
        {
            var settings = new Ninject.NinjectSettings()
            {
                LoadExtensions = false
            };

            _kernel = new Ninject.StandardKernel(settings: settings, modules: new CommonModule());
        }
 public static IKernel CreateKernel()
 {
     try {
         var kernel = new n.StandardKernel(Yaaf.DependencyInjection.Ninject.NinjectKernel.DefaultSettings);
         return(CreateFromKernel(kernel));
     } catch (n.ActivationException err) {
         throw Yaaf.DependencyInjection.Ninject.NinjectKernel.WrapExn(err);
     }
 }
Example #47
0
        static NinjectBootstrapper()
        {
            var kernel = new Ninject.StandardKernel();

            kernel.Settings.AllowNullInjection = true;
            RegisterServices(kernel);
            CommonServiceLocator.ServiceLocator.SetLocatorProvider(() => new Common.Extensions.NinjectServiceLocator(kernel));
            Kernel = kernel;
        }
Example #48
0
 static void Main(string[] args)
 {
     using (var kernal = new Ninject.StandardKernel())
     {
         kernal.Bind <ILogger>().To <ConsoleLogger>();
         var service     = kernal.Get <SalutationService>();
         var mailService = new MailService();
         service.SayHello();
     }
 }
Example #49
0
        public static IEnumerable <object[]> GetContainerAdapters()
        {
            yield return(new object[] { (ResolverFactory)(c =>
                {
                    var container = new DefaultServiceContainer();
                    c(container);
                    return container.Resolve <IServiceResolver>();
                }) });

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

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

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

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

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

            yield return(new object[] { (ResolverFactory)(c =>
                {
                    var container = new NinjectContainer();
                    c(new NinjectAdapter(container));
                    return container.Get <IServiceResolver>();
                }) });
#endif
        }
Example #50
0
    static async Task Main()
    {
        Console.Title = "Samples.UnitOfWork";
        var endpointConfiguration = new EndpointConfiguration("Samples.UnitOfWork");

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

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

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

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

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

        var recoverability = endpointConfiguration.Recoverability();

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

        #region ComponentRegistration

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

        #endregion

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

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

        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Example #51
0
        /// <summary>
        ///     The main entry point of the program. This method initializes the composition root and then launches the game session.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            System.Console.Title = "Card Game";

            var kernel = new Ninject.StandardKernel();

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

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

            gameSessionManager.BeginSession();
        }
Example #52
0
        public void Sum_neg()
        {
            var kernel = new Ninject.StandardKernel();

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

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

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

            Assert.AreEqual(-5, actual);
        }
        public void RegisterRealService()
        {
            using (var standardKernel = new Ninject.StandardKernel())
            {
                NinjectAuto.Register(Contracts.AssemblyInfo.GetExecutingAssembly(), Services.AssemblyInfo.GetExecutingAssembly(), standardKernel);

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

                string writeSomething = service.WriteSomething();

                Assert.AreEqual(writeSomething, "Real Service");
            }
        }
Example #54
0
        public override TInquirer NewInquirer <TInquirer>(Ninject.StandardKernel kernel)
        {
            kernel
            .Bind <UngroupedXileInquirer>()
            .ToSelf().InSingletonScope();
            kernel
            .Bind <UngroupedCentralTendecyInquirer>()
            .ToSelf().InSingletonScope();
            kernel
            .Bind <UngroupedDispersionInquirer>()
            .ToSelf().InSingletonScope();

            return(kernel.Get <TInquirer>());
        }
Example #55
0
 public WCFSorter()
 {
     try
     {
         string[] type_of_sorter = System.IO.File.ReadAllLines(@"Sorter.txt");
         var      kernel         = new Ninject.StandardKernel();
         kernel.Load(type_of_sorter[0]);
         sorter = kernel.Get <ISorter>();
     }
     catch (Exception e)
     {
         System.Console.WriteLine(e.Message);
         System.Console.ReadLine();
     }
 }
        public AugmentationTests()
        {
            var container = new Ninject.StandardKernel();

            container.Bind(x =>
                           x.FromAssemblyContaining(typeof(IAugmentViewModels))
                           .SelectAllClasses()
                           .InheritedFrom <IAugmentViewModels>()
                           .BindAllInterfaces()
                           );

            var services = container.GetAll <IAugmentViewModels>();

            _sut = new UberService(services);
        }
Example #57
0
        public void make_order_with_context_factory_leaves_consistent_db()
        {
            UserTestData.PrepareUser(userId);

            int initialCount;
            int initialUserCount;

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

            MyContext.ResetCounters();

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

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

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

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

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

                Assert.AreEqual(initialUserCount, user.OrdersCount);
                Assert.AreEqual(initialCount, ordersCount);
            }
        }
Example #58
0
 public int[] Sort(int[] array)
 {
     try
     {
         var kernel = new Ninject.StandardKernel();
         kernel.Load("Sort.xml");
         IWCFSorter sorter = kernel.Get <IWCFSorter>();
         return(sorter.Sort(array));
     }
     catch (Exception e)
     {
         System.Console.WriteLine(e.Message);
         System.Console.ReadLine();
         return(null);
     }
 }
Example #59
0
        public void InitApp()
        {
            //инициализация Ninject
            var kernel = new Ninject.StandardKernel(new ViewModel.Ninject.NinjectMainModule());

            _mainViewModel = kernel.Get <MainViewModel>();
            MainWindow     = new MainWindow()
            {
                DataContext = _mainViewModel
            };
            MainWindow.Closed += (s, e) =>
            {
                _mainViewModel.Dispose();
            };
            MainWindow.Show();
        }
Example #60
0
        public void TestMethod1()
        {
            var ker = new Ninject.StandardKernel();

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

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

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

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

            all.Print();
        }