Ejemplo n.º 1
0
        public void GlobalSetup()
        {
            var ninjectSettings = new NinjectSettings
            {
                // Disable to reduce memory pressure
                ActivationCacheDisabled = true,
                LoadExtensions          = false
            };

            _kernelConfiguration = new KernelConfiguration(ninjectSettings);
            _kernelConfiguration.Bind <IWarrior>().To <SpecialNinja>().WhenInjectedExactlyInto <NinjaBarracks>();
            _kernelConfiguration.Bind <IWarrior>().To <Samurai>().WhenInjectedExactlyInto <Barracks>();
            _kernelConfiguration.Bind <IWarrior>().To <FootSoldier>().WhenInjectedExactlyInto <Barracks>();
            _kernelConfiguration.Bind <IWarrior>().To <FootSoldier>();
            _kernelConfiguration.Bind <IWeapon>().To <Shuriken>().WhenInjectedExactlyInto <Barracks>();
            _kernelConfiguration.Bind <IWeapon>().To <Sword>();
            _kernelConfiguration.Bind <ICleric>().To <Monk>();
            _kernelConfiguration.Bind(typeof(ICollection <>)).To(typeof(List <>));
            _kernelConfiguration.Bind(typeof(IList <>)).To(typeof(List <>));
            _kernelConfiguration.Bind <ISingleton>().To <Singleton>().InSingletonScope();
            _kernelConfiguration.Bind <IRouteProvider>().To <RouteProvider>();
            _kernelConfiguration.Bind <IRouteRepository>().To <RouteRepository>();
            _kernelConfiguration.Bind <ITrainPlanner>().To <TrainPlanner>();
            _kernelConfiguration.Bind <IRealtimeEventSource>().To <RealtimeEventSource>();

            _readOnlyKernel = _kernelConfiguration.BuildReadOnlyKernel();
            ClearCache(_readOnlyKernel);
        }
Ejemplo n.º 2
0
        public FakeKernelContainer()
        {
            var kernelConfig = new TestKernel()
                               .CreateKernelConfiguration(new FakeLogger());

            Kernel = kernelConfig.BuildReadonlyKernel();
        }
Ejemplo n.º 3
0
        public CacheBenchmark()
        {
            var ninjectSettings = new NinjectSettings
            {
                // Disable to reduce memory pressure
                ActivationCacheDisabled = true,
                LoadExtensions          = false,
            };

            _cache = new Cache(new Pipeline(Enumerable.Empty <IActivationStrategy>(), new ActivationCache(new NoOpCachePruner())), new NoOpCachePruner());

            _kernelConfiguration                      = new KernelConfiguration();
            _readOnlyKernel                           = _kernelConfiguration.BuildReadOnlyKernel();
            _instanceForScopeWithZeroEntries          = new object();
            _instanceReferenceForScopeWithZeroEntries = new InstanceReference {
                Instance = _instanceForScopeWithZeroEntries
            };

            _scopeWithNoCache = new object();
            _scopeWithOneEntryForBindingConfiguration         = new object();
            _scopeWithZeroEntriesForBindingConfiguration      = new object();
            _scopeWithMoreThanOneEntryForBindingConfiguration = new object();

            _contextWithNoCache = CreateContext(_kernelConfiguration, _readOnlyKernel, typeof(string), _scopeWithNoCache, ninjectSettings);
            _contextWithZeroEntriesForBindingConfiguration      = CreateContext(_kernelConfiguration, _readOnlyKernel, typeof(string), _scopeWithZeroEntriesForBindingConfiguration, ninjectSettings);
            _contextWithOneEntryForBindingConfiguration         = CreateContext(_kernelConfiguration, _readOnlyKernel, typeof(string), _scopeWithOneEntryForBindingConfiguration, ninjectSettings);
            _contextWithMoreThanOneEntryForBindingConfiguration = CreateContext(_kernelConfiguration, _readOnlyKernel, typeof(string), _scopeWithMoreThanOneEntryForBindingConfiguration, ninjectSettings);
        }
Ejemplo n.º 4
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // for ninject only
            kernel = RegisterApplicationComponents(app, loggerFactory);

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Checkes whether a binding exists for a given target on the specified kernel.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        /// <param name="context">The context.</param>
        /// <param name="target">The target.</param>
        /// <returns>Whether a binding exists for the target in the given context.</returns>
        protected virtual bool BindingExists(IReadOnlyKernel kernel, IContext context, ITarget target)
        {
            var targetType = this.GetTargetType(target);

            return(kernel.GetBindings(targetType).Any(b => !b.IsImplicit) ||
                   target.HasDefaultValue);
        }
Ejemplo n.º 6
0
        private static void ClearCache(IReadOnlyKernel readOnlyKernel)
        {
            var bindingCacheField = typeof(ReadOnlyKernel).GetField("bindingCache", BindingFlags.NonPublic | BindingFlags.Instance);
            var cache             = (Dictionary <Type, IBinding[]>)bindingCacheField.GetValue(readOnlyKernel);

            // var cache = (Dictionary<Type, ICollection<IBinding>>)bindingCacheField.GetValue(readOnlyKernel);
            cache.Clear();
        }
Ejemplo n.º 7
0
        public NinjectBenchmark()
        {
            var config = new KernelConfiguration();

            config.Bind <ISingleton>().To <Singleton>().InSingletonScope();
            config.Bind <ITransient>().To <Transient>().InTransientScope();
            config.Bind <ICombined>().To <Combined>().InTransientScope();
            kernel = config.BuildReadonlyKernel();
        }
Ejemplo n.º 8
0
        public static INForumApplicationBuilder WithNinject(this INForumApplicationBuilder app)
        {
            IKernelConfiguration config = new KernelConfiguration();

            // Register application services
            config.Bind(app.ApplicationBuilder.GetControllerTypes()).ToSelf().InScope(RequestScope);

            config.Bind <IUserService>().To <AspNetUserService>().InScope(RequestScope);
            //config.Bind<CustomMiddleware>().ToSelf();

            // Cross-wire required framework services
            config.BindToMethod(app.GetRequestService <IViewBufferScope>);
            //config.Bind<ILoggerFactory>().ToConstant(loggerFactory);

            config.Bind <ICommandDispatcher>().To <CommandDispatcher>();
            config.Bind <IQueryDispatcher>().To <QueryDispatcher>();

            config.Bind <IHttpContextAccessor>().ToMethod((context) => {
                return(app.ApplicationServices.GetRequiredService <IHttpContextAccessor>());
            }).InScope(RequestScope);

            config.Bind <IPrincipal>().ToMethod((context) => {
                return(context.Kernel.Get <IHttpContextAccessor>().HttpContext.User);
            }).InScope(RequestScope);

            config
            .Bind(typeof(IGenericValidationCommandHandlerDecorator <>))
            .To(typeof(GenericValidationCommandHandlerDecorator <>));
            config
            .Bind(typeof(IGenericPermissionCheckCommandHandlerDecorator <>))
            .To(typeof(GenericPermissionCheckCommandHandlerDecorator <>));

            config
            .Bind(typeof(IGenericValidationQueryHandlerDecorator <,>))
            .To(typeof(GenericValidationQueryHandlerDecorator <,>));
            config
            .Bind(typeof(IGenericPermissionCheckQueryHandlerDecorator <,>))
            .To(typeof(GenericPermissionCheckQueryHandlerDecorator <,>));

            Assembly coreAssembly = typeof(NForum.CQS.CommandWithStatus).GetTypeInfo().Assembly;

            config.BindQueryHandlers(coreAssembly);

            config.BindCommandHandlers(coreAssembly);

            config.BindPermissionChecks(coreAssembly);

            config.BindValidators(coreAssembly);

            kernel = config.BuildReadonlyKernel();

            return(builder);
        }
Ejemplo n.º 9
0
        public bool RunSmallExamples()
        {
            bool result = RunExamples(GetSmallExamples());

            log.InfoFormat(
                "Small examples {0}, errors: {1}",
                Name, !result);

            IReadOnlyKernel configuration = Core.AppContext.GetConfiguration();
            AppStatistics   appStatistics = configuration.Get <AppStatistics>();

            appStatistics.ThereWereErrors = (appStatistics.ThereWereErrors || !result);

            return(result);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Context"/> class.
        /// </summary>
        /// <param name="readonlyKernel">The kernel managing the resolution.</param>
        /// <param name="request">The context's request.</param>
        /// <param name="binding">The context's binding.</param>
        /// <param name="cache">The cache component.</param>
        /// <param name="planner">The planner component.</param>
        /// <param name="pipeline">The pipeline component.</param>
        public Context(IReadOnlyKernel readonlyKernel, IRequest request, IBinding binding, ICache cache, IPlanner planner, IPipeline pipeline)
        {
            this.Kernel     = readonlyKernel;
            this.Request    = request;
            this.Binding    = binding;
            this.Parameters = request.Parameters.Union(binding.Parameters).ToList();
            this.Cache      = cache;
            this.Planner    = planner;
            this.Pipeline   = pipeline;

            if (binding.Service.GetTypeInfo().IsGenericTypeDefinition)
            {
                this.HasInferredGenericArguments = true;
                this.GenericArguments            = request.Service.GetTypeInfo().GenericTypeArguments;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Context"/> class.
        /// </summary>
        /// <param name="readonlyKernel">The kernel managing the resolution.</param>
        /// <param name="request">The context's request.</param>
        /// <param name="binding">The context's binding.</param>
        /// <param name="cache">The cache component.</param>
        /// <param name="planner">The planner component.</param>
        /// <param name="pipeline">The pipeline component.</param>
        public Context(IReadOnlyKernel readonlyKernel, IRequest request, IBinding binding, ICache cache, IPlanner planner, IPipeline pipeline)
        {
            this.Kernel = readonlyKernel;
            this.Request = request;
            this.Binding = binding;
            this.Parameters = request.Parameters.Union(binding.Parameters).ToList();
            this.Cache = cache;
            this.Planner = planner;
            this.Pipeline = pipeline;

            if (binding.Service.GetTypeInfo().IsGenericTypeDefinition)
            {
                this.HasInferredGenericArguments = true;
                this.GenericArguments = request.Service.GetTypeInfo().GenericTypeArguments;
            }
        }
Ejemplo n.º 12
0
        private static void Main()
        {
            var kernelConfig = new KernelConfiguration();

            kernelConfig.Bind <IMessageService>().To <ConsoleMessageService>();

            Kernel = kernelConfig.BuildReadonlyKernel();

            Task.Run(MainAsync).Wait();

            while (Console.KeyAvailable)
            {
                Console.ReadKey(true);                   // clear buffer
            }
            Console.WriteLine("Press any key to continue");
            Console.ReadKey(true);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            kernel = RegisterApplicationComponents(app, loggerFactory);

            // Add custom middleware
            app.Use(async(context, next) =>
            {
                await kernel.Get <CustomMiddleware>().Invoke(context, next);
            });

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        private object GetInstanceHelper(Type controllerType, Type injectModule)
        {
            //Değişken modüller çakışmaması için ilk önce siliniyor.
            //Gelen parametrelere göre yeni modüller yükleniyor.
            CleanModules(); //Aspect Olabilir.

            //Modüller dizizinden istenilen modül alınıyor.
            var module = _veriableModules.SingleOrDefault(x => x.Name == injectModule.FullName);

            //IKernel'a mdül yüklenir.
            _kernelConfiguration.Load(module);

            //Kernel tekrar build edilir.
            _kernel = _kernelConfiguration.BuildReadonlyKernel();

            //Instance alınır.
            var instance = _kernel.Get(controllerType);

            return(instance);
        }
        /// <summary>
        /// Checks whether a binding exists for a given target on the specified kernel.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        /// <param name="context">The context.</param>
        /// <param name="target">The target.</param>
        /// <returns>
        /// <see langword="true"/> if a binding exists for the target in the given context; otherwise,
        /// <see langword="false"/>.
        /// </returns>
        protected virtual bool BindingExists(IReadOnlyKernel kernel, IContext context, ITarget target)
        {
            if (target.HasDefaultValue)
            {
                return(true);
            }

            var targetType = GetTargetType(target);
            var bindings   = kernel.GetBindings(targetType);

            if (bindings.Length > 0)
            {
                var request = context.Request.CreateChild(targetType, context, target);
                foreach (var binding in bindings)
                {
                    if (!binding.IsImplicit && binding.Matches(request))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 16
0
        public void SetupForSingletonTest()
        {
            _config = new KernelConfiguration();

            _config.Bind <IRepository>().To <Repository>().InSingletonScope();
            _config.Bind <IAuthenticationService>().To <AuthenticationService>().InSingletonScope();
            _config.Bind <UserController>().ToSelf().InSingletonScope();

            _config.Bind <IWebService>().To <WebService>().InSingletonScope();
            _config.Bind <IAuthenticator>().To <Authenticator>().InSingletonScope();
            _config.Bind <IStockQuote>().To <StockQuote>().InSingletonScope();
            _config.Bind <IDatabase>().To <Database>().InSingletonScope();
            _config.Bind <IErrorHandler>().To <ErrorHandler>().InSingletonScope();

            _config.Bind <IService1>().To <Service1>().InSingletonScope();
            _config.Bind <IService2>().To <Service2>().InSingletonScope();
            _config.Bind <IService3>().To <Service3>().InSingletonScope();
            _config.Bind <IService4>().To <Service4>().InSingletonScope();

            _config.Bind <ILogger>().To <Logger>().InSingletonScope();

            _kernel?.Dispose();
            _kernel = _config.BuildReadonlyKernel();
        }
Ejemplo n.º 17
0
 public NinjectServiceLocator(IReadOnlyKernel kernel)
 {
     Kernel = kernel;
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Checkes whether a binding exists for a given target on the specified kernel.
 /// </summary>
 /// <param name="kernel">The kernel.</param>
 /// <param name="context">The context.</param>
 /// <param name="target">The target.</param>
 /// <returns>Whether a binding exists for the target in the given context.</returns>
 protected virtual bool BindingExists(IReadOnlyKernel kernel, IContext context, ITarget target)
 {
     var targetType = this.GetTargetType(target);
     return kernel.GetBindings(targetType).Any(b => !b.IsImplicit)
            || target.HasDefaultValue;
 }