protected virtual void AddRegistration(WindsorContainer container) { container.Register(Component.For<ISecurityAssertionProvider>().Instance(new SafeMethodOnlySecurityAssertionProvider())); // Use the version of the interceptor that doesn't allow any calls to go through // container.Register(Component.For<IInterceptor, ApplyViewPermissionsWithNoProceedInterceptor>()); IoC.Initialize(container); container.Register( Component .For(typeof(IMetricActionUrlAuthorizationProvider)) .Instance(metricActionUrlAuthService)); container.Install(new TestConfigurationSpecificInstaller()); container.Install(new SecurityComponentsInstaller(typeof(ApplyViewPermissionsByClaimWithNoProceedInterceptor))); container.Install(new MetricServiceInstaller()); container.Install(new GenericServiceInstaller<Marker_EdFi_Dashboards_Warehouse_Resources>()); container.Install(new GenericServiceInstaller<Marker_EdFi_Dashboards_Resources>()); container.Install(new RepositoryInstaller<Marker_EdFi_Dashboards_Data>()); container.Install(new RepositoryInstaller<Marker_EdFi_Dashboards_Metric_Data_Entities>()); container.Install(new PersistedRepositoryInstaller<Marker_EdFi_Dashboards_Application_Data>()); container.Install(new QueryInstaller<Marker_EdFi_Dashboards_Data>()); container.Install(new RepositoryInstaller<Marker_EdFi_Dashboards_Warehouse_Data>()); container.Register( Classes.FromAssembly(securityAssembly) .BasedOn<IAuthorizationDelegate>() .WithService.FirstInterface(), Component.For<AuthorizationDelegateMap>()); // Register the wrapped service locator singleton instance container.Register( Component.For<IServiceLocator>() .Instance(IoC.WrappedServiceLocator)); }
public IntegrationContainer() { container = new WindsorContainer(); // allow collection injection container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel)); // disable automatic property injection container.Kernel.ComponentModelBuilder.RemoveContributor( container.Kernel.ComponentModelBuilder.Contributors.OfType<PropertiesDependenciesModelInspector>().Single()); container.Kernel.AddFacility<TypedFactoryFacility>(); //selectively install Finance.Service classes container.Install( new MappingsCreatorInstaller() //new MappingsInstaller() ); //Persistence.EF installers container.Install(FromAssembly.Containing<ModelContextFactory>()); //Core installers container.Install(FromAssembly.Containing<AppSettings>()); //Integration inplememntations container.Register(Component.For<IConnection>().ImplementedBy<IntegrationConnection>()); container.Register(Component.For<IExceptionService>().ImplementedBy<IntegrationExceptionService>()); //Create all mappings container.Resolve<MappingsCreator>(); DisplayRegistrations(); }
private void InitializeWindsor() { _windsorContainer = new WindsorContainer(); _windsorContainer.Install(FromAssembly.Containing<DependencyInstaller>()); _windsorContainer.Install(FromAssembly.This()); GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(_windsorContainer.Kernel); }
public void Resolve_WithInstaller_ShouldBeNotNull() { var container = new WindsorContainer(); var directory = AppDomain.CurrentDomain.BaseDirectory; var finder = AssemblyFinder.Builder.UsePath(directory).Create; container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel)); container.Install(new ServiceLocatorInstaller()); var assemblies = finder.GetAssembliesTagged<AssemblyTagAttribute>(); container.Install(new FactoryInstaller(assemblies)); var instance = container.Resolve<IObjectFactory>(); instance.ShouldNotBeNull(); instance.ConfigurationProvider.Configuration.Items.ShouldNotBeEmpty(); instance.ConfigurationProvider.Configuration.Items.Count.ShouldBe(1); instance.ConfigurationProvider.Sources.ShouldNotBeEmpty(); instance.ConfigurationProvider.Sources.Length.ShouldBe(2); instance.ShouldBeAssignableTo<IObjectFactory>(); instance.ShouldBeOfType<ObjectFactory>(); }
public static void PreStart() { var container = new WindsorContainer(); container.Install(new DataAccessInstaller()); container.Install(new CoreInstaller()); container.Install(new ControllerInstaller()); }
private void InitializeWindsor() { _windsorContainer = new WindsorContainer(); _windsorContainer.Install(FromAssembly.Containing<DependencyInstaller>()); _windsorContainer.Install(FromAssembly.This()); ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_windsorContainer.Kernel)); }
static IWindsorContainer CreateContainer() { IWindsorContainer container = new WindsorContainer(); container.Install(FromAssembly.InThisApplication()); container.Install(new DefaultHandlerInstaller()); return container; }
private void button1_Click(object sender, EventArgs e) { IWindsorContainer container = new WindsorContainer(); container.Install(Configuration.FromAppConfig()); container.Install(FromAssembly.Named("com.Sconit.BatchJob.WindowsService")); IJobRunMgr jobRunMgr = container.Resolve<IJobRunMgr>(); jobRunMgr.RunBatchJobs(container); container.Dispose(); }
public void Startable_and_components_in_separate_Install_Startable_last_works() { using (var container = new WindsorContainer()) { container.AddFacility<StartableFacility>(f => f.DeferredStart()); container.Install(new DependenciesInstaller()); container.Install(new StartableInstaller()); } }
internal static void Main() { IWindsorContainer container = new WindsorContainer(); container.Install(FromAssembly.InDirectory(new AssemblyFilter("Commands"))); container.Install(FromAssembly.This()); var interpretor = container.Resolve<CommandInterpreter>(); interpretor.Run(); }
public void Start() { _windsorContainer = new WindsorContainer(); _windsorContainer.Install(FromAssembly.Containing<PhoneBookDependencyInstaller>()); _windsorContainer.Install(FromAssembly.This()); _windsorContainer.Resolve<IPeriodicServiceTrigger>().Start(); }
public void Initialize(string filename) { using (var container = new WindsorContainer()) { container.Install(FromAssembly.Containing<DapperInstaller>()); container.Install(FromAssembly.Containing<ServicesInstaller>()); var importService = container.Resolve<ITransactionImportService>(); importService.Import(filename); } }
private IWindsorContainer CreateContainer() { var container = new WindsorContainer(); container.Install(new PersistenceInstaller()); container.Install(new ServicesInstaller()); container.Install(new ControllersInstaller()); container.Install(new HubsInstaller()); return container; }
protected void Application_Start() { var container = new WindsorContainer(); container.Install(new WebInstaller()); container.Install(new BusInstaller()); ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container)); AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); }
private void InitializeWindsor() { _windsorContainer = new WindsorContainer(); _windsorContainer.Install(FromAssembly.Containing<DependencyInstaller>()); _windsorContainer.Install(FromAssembly.This()); ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_windsorContainer.Kernel)); //register web api dependency resolver GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(_windsorContainer.Kernel); //filter System.Web.HttpContext.Current.Application["Windsor"] = _windsorContainer; }
public static IWindsorContainer Bootstrap() { XmlConfigurator.Configure(); var container = new WindsorContainer(); container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true)); container.Install(new ControllerRegistry()); container.Install(new BuildScreenRegistry()); var controllerFactory = new WindsorControllerFactory(container.Kernel); ControllerBuilder.Current.SetControllerFactory(controllerFactory); return container; }
private void InitContainer() { var container = new WindsorContainer(); ServiceLocator.SetLocatorProvider(() => new CommonServiceLocator.WindsorAdapter.WindsorServiceLocator(container)); container.Install(new InfrastructureInstaller()); container.Install(new EventStoreInstaller()); container.Install(new InventoryInstaller()); container.Register(Classes.FromThisAssembly().BasedOn<Controller>().LifestyleTransient()); ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container.Kernel)); }
public static IDependencyInjectionContainer Compose() { // Create the DI container var container = new WindsorContainer(); // Setup configuration of DI container.Install(new MvcSiteMapProviderInstaller()); container.Install(new MvcInstaller()); // Return our DI container wrapper instance return new WindsorDependencyInjectionContainer(container); }
public static IWindsorContainer Register() { var container = new WindsorContainer(); ServiceLocator.SetLocatorProvider(() => new CommonServiceLocator.WindsorAdapter.WindsorServiceLocator(container)); container.Install(new InfrastructureInstaller()); container.Install(new EventStoreInstaller()); container.Install(new InventoryInstaller()); container.Install(new WebApiInstaller()); return container; }
public void Startable_and_components_in_separate_Install_Startable_first_throws() { using (var container = new WindsorContainer()) { container.AddFacility<StartableFacility>(f => f.DeferredStart()); Assert.Throws<HandlerException>(() => { container.Install(new StartableInstaller()); container.Install(new DependenciesInstaller()); }); } }
private void InitilizeWindsor(HttpConfiguration configuration) { _windContainer = new WindsorContainer(); _windContainer.Install(FromAssembly.This()); _windContainer.Kernel.Resolver.AddSubResolver( new CollectionResolver(_windContainer.Kernel,true)); var dependencyResolver=new WindsorDependencyResolver(_windContainer); configuration.DependencyResolver=dependencyResolver; _windContainer.Install(FromAssembly.Containing<DependencyInstaller>()); //ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_windContainer.Kernel)); //ApiControllerBuilder }
protected void Application_Start() { var container = new WindsorContainer(); container.Install(new WebInstaller()); container.Install(new BusInstaller()); ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container)); //var controller = container.Resolve<SignupController>(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
static void Main(string[] args) { Console.WriteLine("Using anonymous type"); using (var container = new WindsorContainer()) { container.Install(new InfrastructureInstaller()); container.Install(new Installer()); var factory = container.Resolve<IViewModelFactory>(); factory.Create<ListViewModel>(); } Console.WriteLine("Press any key..."); Console.ReadKey(); }
public void Should_resolve_sync_json_client_from_windsor() { var container = new WindsorContainer(); container.Install(new EndersJson.Windsor.WindsorInstaller()); Assert.That(container.Resolve <ISyncJsonService>(), Is.Not.Null); }
public void InstallShouldThrowExceptionFromFailedInstaller() { using (var container = new WindsorContainer()) { container.AddFacility<StartableFacility>(f => f.DeferredStart()); // I would expect NotImplementedException to be thrown here // because it is thrown in the install method of the ExceptionThrowingInstaller // however, what appears to be happening is that after the NotImplementedException // is thrown, the DependencyInstaller never runs, but the "deferred start" code // in OptimizeDependencyResolutionDisposable.Dispose() kicks in anyway // and tries to create the StartableComponent, which it fails to do // because IDependencyOfStartableComponent is not registered // The net effect is that the NotImplementedException thrown by ExceptionThrowingInstaller // is "swallowed" and instead I see a Kernel HandlerException telling me that // IDependencyOfStartableComponent is not registered // expected : Assert.Throws<NotImplementedException>( () => container.Install(new ActionBasedInstaller(c => c.Register(Component.For<UsesIEmptyService>().Start())), new ActionBasedInstaller(c => { throw new NotImplementedException(); }), new ActionBasedInstaller(c => c.Register(Component.For<IEmptyService>().ImplementedBy<EmptyServiceA>())))); } }
public ActionResult GetData(int start, int limit) { ListingUsers listingUsers = new ListingUsers(); var cont = new WindsorContainer(); cont.Install(new CastleWidsorConfiguration()); IMasterGetDataTable masterConnection = cont.Resolve <IMasterGetDataTable>(); ISqlMaster sqlMaster = cont.Resolve <ISqlMaster>(); List <Users> users = masterConnection.GetDataTable(sqlMaster.GetAllColumn()); int startIndex = start; int Limit = limit; int totalLimit = users.Count - start; if (totalLimit < Limit) { Limit = totalLimit; } List <Users> newUsers = new List <Users>(); for (int i = 0; i < Limit; i++) { newUsers.Add(users[startIndex]); startIndex++; } listingUsers.total = users.Count; listingUsers.newUsers = newUsers; return(Json(listingUsers, JsonRequestBehavior.AllowGet)); }
static void Main(string[] args) { using (var container = new WindsorContainer()) { container.Install(new AssmInstaller()); var person = container.Resolve <IPerson>(); person.Say(); var task = container.Resolve <ITask>(); var task2 = container.ResolveAll <ITask>().FirstOrDefault(x => x.GetType() == typeof(Task2)); task.Run(); task2.Run(); } DependencyResolver.Initialize(); //resolve the type:Rocket var rocket = DependencyResolver.For <IRocket>(); //method call try { var result = rocket.Launch(5); Console.WriteLine(result); } catch (Exception ex) { } System.Console.ReadKey(); }
protected void Application_Start() { Container = new WindsorContainer(); Container.Install(new DependencyInstaller()); GlobalConfiguration.Configure(WebApiConfig.Register); }
static void Main(string[] args) { using (var container = new WindsorContainer()) { container.Install( new Startup.RebusInstaller() ); var service = container.Resolve <OldRebusService>(); HostFactory.Run(x => { x.SetServiceName("RebusTestOld"); x.SetDescription("Old Rebus Test"); x.StartAutomatically(); x.RunAsLocalSystem(); x.Service(() => service, s => { s.AfterStartingService(ctx => { Console.WriteLine("Initialized"); }); }); }); } }
public IModule LoadModule(Assembly assembly) { try { var moduleInstaller = FromAssembly.Instance(assembly); var windsorContainer = new WindsorContainer(); _mainContainer.AddChildContainer(windsorContainer); windsorContainer.Install(moduleInstaller); var module = windsorContainer.Resolve <IModule>(); if (!AssemblySource.Instance.Contains(assembly)) { AssemblySource.Instance.Add(assembly); } return(module); } catch (Exception) { //TODO: good exception handling return(null); } }
private void InitializeWindsor() { _windsorContainer = new WindsorContainer(); _windsorContainer.Install(FromAssembly.This()); ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_windsorContainer.Kernel)); }
public static void Main(string[] args) { var container = new WindsorContainer (); container.Install (new ServicesInstaller ()); container.Resolve<DemoApp> ().Run (); }
static void Main() { Migrate.Database("database", options: new Options().UseVersionTableName("__DatabaseVersion")); using (var container = new WindsorContainer()) { // run Windsor installers - they're in the UnitOfWork.Installers namespace container.Install(FromAssembly.This()); Configure.With(new CastleWindsorContainerAdapter(container)) .Transport(t => t.UseMsmq("uow.test")) .Options(o => { // run the potentially failing handler last to demonstrate // that the uow is not committed, even though the error // happes after the insert o.SpecifyOrderOfHandlers() .First <InsertRowsIntoDatabase>() .Then <FailSometimes>(); }) .Start(); using (var timer = new Timer(1000)) { timer.Elapsed += (o, ea) => SendStringToSelf(container); timer.Start(); Console.WriteLine("Press ENTER to quit"); Console.ReadLine(); } } }
static void Main() { _container = new WindsorContainer(); _container.Install(FromAssembly.This()); _game = _container.Resolve <IGame>(); _game.SendMessage += RenderMessage; IStrategy _strategy = _container.Resolve <IStrategy> (); _strategy.SubscribeToGame(_game); Task.Factory.StartNew(() => _game.Start()); _window = new RenderWindow(VideoMode.DesktopMode, "Test"); _window.Closed += OnClosed; _window.KeyPressed += OnKeyPressed; _renderer = new Renderer(_window); while (_window.IsOpen()) { _window.DispatchEvents(); _window.Clear(); _renderer.RenderCalendar(_game.Calendar); if (_game.Scene != null) { _renderer.RenderScene(_game.Scene); } _renderer.RenderMessage(_message); _window.Display(); } _container.Dispose(); Console.ReadKey(); }
static void Main(string[] args) { NLogLogger.Use(); Logger.Configure(x => x.UseNLogLogger()); WindsorContainer container = new WindsorContainer(); container.AddFacility <LoggingFacility>(f => f.LogUsing(LoggerImplementation.NLog)); container.Install(FromAssembly.This()); container.Register(Component.For <Server>().LifestyleSingleton()); Host host = HostFactory.New(conf => { conf.Service <Server>(s => { s.ConstructUsing(name => { return(container.Resolve <Server>()); }); s.WhenStarted(program => program.Start()); s.WhenStopped(program => program.Stop()); }); conf.RunAsLocalSystem(); conf.SetServiceName("PluginFramework-Server"); conf.SetDescription("Server for the plugin framework"); conf.SetDisplayName("PluginFramework-Server"); conf.UseNLog(); }); host.Run(); }
private static void Init() { // application starts... _container = new WindsorContainer(); /*_container.Register( * Classes * .FromThisAssembly() * .BasedOn<ApiController>() * .LifestyleScoped() * );*/ // _container.Install(FromAssembly.This()); /*_container.Register(Classes.FromThisAssembly() * .BasedOn<IHttpController>() * .LifestylePerThread());*/ /*_container.Register( * Classes * .FromThisAssembly() * .BasedOn<ApiController>() * .LifestyleScoped() * );*/ _container.Install( new RepositoriesInstaller() // and all your other installers ); }
public void Windsor_Can_Resolve_All_Command_And_Query_Classes() { // Setup Assembly asm = Assembly.GetAssembly(typeof(IUnitOfWork)); IList <Type> classTypes = Assembly.GetAssembly(typeof(MJLConstants)) .GetTypes() .Where(x => !x.IsDefined(typeof(CompilerGeneratedAttribute), false)) .Where(x => x.Namespace.StartsWith("MyJobLeads.DomainModel.Commands") || x.Namespace.StartsWith("MyJobLeads.DomainModel.Queries")) .Where(x => x.IsClass && !x.IsDefined(typeof(CompilerGeneratedAttribute), false)) .Distinct() .ToList(); IWindsorContainer container = new WindsorContainer(); container.Kernel.ComponentModelBuilder.AddContributor(new SingletonLifestyleEqualizer()); container.Install(FromAssembly.Containing <HomeController>()); string assertOutput = "The following types could not be resolved: " + Environment.NewLine; int failureCount = 0; // Act foreach (Type t in classTypes) { try { container.Resolve(t); } catch (ComponentNotFoundException) { assertOutput += t.FullName + Environment.NewLine; failureCount++; } } // Verify Assert.IsTrue(failureCount == 0, assertOutput + string.Format("{0} classes missing from Windsor", failureCount)); }
static void Main(string[] args) { var container = new WindsorContainer(); container.Register(Component.For <IWindsorContainer>().Instance(container).LifeStyle.Singleton); container.Register(Component.For <IServiceLocator> ().ImplementedBy <WindsorServiceLocator>().LifeStyle.Singleton); container.Install(FromAssembly.This(), FromAssembly.InDirectory(new AssemblyFilter(".", "*Logger*")) ); /* * foreach ( var handler in container.Kernel.GetAssignableHandlers(typeof(object))) * { * Console.WriteLine("Registered: {0} for {1} (lifestyle: {2})", * handler.ComponentModel.Implementation.FullName, * String.Join(", ", handler.ComponentModel.Services.Select(t => t.FullName)), * handler.ComponentModel.LifestyleType); * } */ ServiceLocator.SetLocatorProvider(() => container.Resolve <IServiceLocator>()); var logger = ServiceLocator.Current.GetInstance <ILogger>(); logger.Log("Helo World"); Console.ReadKey(); }
public void containerCreate() { container = new WindsorContainer(); container.Install(new ConfigurationCastleWindsorTest()); writerServers = container.Resolve <IWriterServers>(); StubtServerObjs = container.Resolve <IServerObj>(); }
public static void Registrate() { var container = new WindsorContainer(); var dataLayerAssemblyName = "EndowmentDataLayer"; var dataLayerNameEndComponents = new[] { "Factory", "Handler" }; var dataLayerNameContains = new[] { "Endowment" }; var webAppAssemblyName = "EndowmentWebApp"; var webAppNameEndComponents = new[] { "Builder", "Service" }; var webAppNamespaceContainComponents = new[] { "Infrastructure" }; var windsorCommonInstaller = new WindsorCommonInstaller(); windsorCommonInstaller .NameEndWith(dataLayerAssemblyName, dataLayerNameEndComponents) .NameContains(dataLayerAssemblyName, dataLayerNameContains) .NameEndWith(webAppAssemblyName, webAppNameEndComponents) .NamespaceContains(webAppAssemblyName, webAppNamespaceContainComponents); var windsorInstallers = windsorCommonInstaller.GetInstallers().ToList(); var listInstaller = new List<IWindsorInstaller> { new InfrastructureProjectWindsorInstaller(), new RepositorySingletonInstaller(ActivatorDbForWindsor.TypeOfEntity, typeof (TestEndowmentRepository)), new WindsorInstallerTestClasses() }; windsorInstallers.AddRange(listInstaller); container.Install(windsorInstallers.ToArray()); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { // Only allow access if the user is a site administrator if (Membership.GetUser() != null) { var container = new WindsorContainer(); container.Install(FromAssembly.Containing <RequiresSiteAdminAttribute>()); var process = container.Resolve <IProcess <SiteAdminAuthorizationParams, AuthorizationResultViewModel> >(); int userId = (int)Membership.GetUser().ProviderUserKey; var result = process.Execute(new SiteAdminAuthorizationParams { UserId = userId }); if (result.UserAuthorized) { return; } } // User wasn't logged in or not a site administrator, so redirect to the homepage filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" }, { "area", "" } }); }
protected void Application_Start() { var container = new WindsorContainer(); container.Install(new WebInstaller()); container.Install(new BusInstaller()); ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container)); //var controller = container.Resolve<SignupController>(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var container = new WindsorContainer(); container.Install(new MessagingInstaller()); container.Register( Component.For <ConnectionConfiguration>() .Instance(new ConnectionConfiguration { Protocol = "amqps", HostName = "localhost", Exchange = "test", PoisionExchange = "poision", PoisionQueueName = "poision-queue", UndeliveredExchange = "undelivered", UndeliveredQueueName = "undelivered-queue", //Port = 5672 Port = 5671, UserName = "******", Password = "******" }), Component.For <IMessageLogger>() .ImplementedBy <ConsoleMessageLogger>() .LifestyleSingleton()); var dispatcher = container.Kernel.Resolve <IMessageDispatcher>(); dispatcher.Send(new TestMessage { Id = 2 }); Console.ReadKey(); }
private void Application_Startup(object sender, StartupEventArgs e) { container.Install(FromAssembly.This()); using (var c = new Context()) { try { c.Database.CanConnect(); } catch (Exception ex) { MessageBox.Show($"Błąd podłączenia z bazą danych\r\n{ ex.Message}"); Environment.Exit(0); } } //var view = container.Resolve<WindowTestRaf>(); var view = container.Resolve <MainView>(); //var view = container.Resolve<Window2>(); view.Show(); //container.Dispose(); }
public static void Register(HttpConfiguration config) { //Windsor and IOC var _container = new WindsorContainer(); //Use the Installers in this Assembly (public classes who inherit from IWindsorInstaller //Also use installers defined in the App.config _container.Install(FromAssembly.This(), Configuration.FromAppConfig()); _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel, true)); var dependencyResolver = new WindsorDependencyResolver(_container); config.DependencyResolver = dependencyResolver; // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); var jsonFormatter = config.Formatters.OfType <JsonMediaTypeFormatter>().FirstOrDefault(); if (jsonFormatter != null) { jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } }
private HttpConfiguration Register() { var container = new WindsorContainer(); container.Install( new DatabaseInstaller(), new ApplicationInstaller()); var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*")); config.Filters.Add(new ModelStateValidationFilterAttribute()); config.Filters.Add(new NotFoundExceptionFilterAttribute()); container.AddFacility <AspNetWebApiFacility>(x => x.UsingConfiguration(config).UsingSelfHosting()); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false; config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None; return(config); }
public IDependencyResolver Module() { var container = new WindsorContainer(); container.Install(new ImplementationModule()); return(new DependencyResolver(container)); }
public IModule Load(Assembly assembly) { try { var moduleInstaller = FromAssembly.Instance(assembly); var modulecontainer = new WindsorContainer(); _container.AddChildContainer(modulecontainer); modulecontainer.Install(moduleInstaller); var module = modulecontainer.Resolve <IModule>(); //If ViewModel can't find View, we need to add loaded assemblies if (!AssemblySource.Instance.Contains(assembly)) { AssemblySource.Instance.Add(assembly); } return(module); } catch (Exception exception) { _logger.Error(exception); return(null); } }
private static void Main(string[] args) { if (args.Length > 0 && args[0].Equals("service", StringComparison.CurrentCultureIgnoreCase)) { ServiceBase.Run(new ServiceBase[] { new Service() }); } else { Logger.Info("Starting Autobot in console mode"); try { using (var container = new WindsorContainer()) { container.Install(Configuration.FromAppConfig()); var botEngine = container.Resolve<AutoBotEngine>(); botEngine.Start(); // "start" is synchronous so we'll use a manual reset event // to pause this thread forever. client events will continue to // fire but we won't have to worry about setting up an idle "while" loop. var waiter = new ManualResetEvent(false); waiter.WaitOne(); } } catch (Exception ex) { Logger.Error("ERROR!:", ex); } } }
public async Task Run(string[] args) { string filePath; int amount; if (ValidateAndMapArguments(args, out filePath, out amount)) { int lengthOfLoan = 36; var container = new WindsorContainer(); container.Install(new CoreInstaller()); var lenderFactory = container.Resolve <ILenderFactory>(); var loanCalculator = container.Resolve <IQuoteCalculatorService>(); var lenders = await lenderFactory.CreateLendersFromCsvFileAsync(filePath); var loanResult = loanCalculator.CalculateQuote(amount, lengthOfLoan, lenders); Outputresult(loanResult, amount); } else { Console.WriteLine("Incorrect usage, to run: LoanCalculator.Cli.exe <path to csv market file> <amount that is multiple of 100>"); } }
public static int Main(string[] args) { string configurationFile = "configuration.xml"; if (args.Length >= 1) { configurationFile = args[0]; } if (!File.Exists(configurationFile)) { Console.WriteLine("Configuration file does not exist!"); return(1); } Console.WriteLine($"Welcome to EyeInTheSky v{FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion}!"); container = new WindsorContainer(configurationFile); container.Install(FromAssembly.This(), Configuration.FromXmlFile("modules.xml")); var app = container.Resolve <IApplication>(); app.Run(); container.Release(app); return(0); }
public static IWindsorContainer Initialize(ApplicationConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } WindsorContainer container = new WindsorContainer(); container.Kernel.AddFacility <TypedFactoryFacility>(); container.Register(new IRegistration[1] { Component.For <ILazyComponentLoader>().ImplementedBy <LazyOfTComponentLoader>() }); configuration.Extensibility(extensibility => { using (IEnumerator <IInitializable <IWindsorContainer> > enumerator = extensibility.OfType <IInitializable <IWindsorContainer> >().GetEnumerator()) { while (enumerator.MoveNext()) { enumerator.Current.Initialize(container); } } }); container.Install(new IWindsorInstaller[1] { Install.ByConvention.AddFromAssemblyOfThis <ConventionInstaller>().Ignore <IApplicationContext>().Ignore <IHost>().Ignore <ITask>().Ignore <IStep>() }); return(container); }
private static IWindsorContainer BootstrapContainer() { IWindsorContainer container = new WindsorContainer(); container.Install(FromAssembly.This()); return(container); }
public static IWindsorContainer Bootstrap() { // Create an IWindsorContainer instance, also including the Typed Factory Facility. // Facilities are a means of extending Castle Windsor behavior, there are a few that // come 'in the box', and users can implement their own facilities also. // // The TypedFactoryFacility is what enables us to register factory interfaces // and have Windsor automatically generate corresponding factory classes for us // at runtime. var container = new WindsorContainer().AddFacility <TypedFactoryFacility>(); // By default, Windsor will also resolve property dependencies (i.e. it will // inject default values into properties). This behavior can cause some interesting // issues, and it's only very rarely useful, so we'll tell the container to // turn off this behavior. WindsorContainerHelper.DisableDefaultPropertyInjectionBehavior(container); // And here is where the magic happens... // Container.Install kicks off the actual type registration process, and it works like this: // // FromAssembly.This() tells the container "Hey container, I want you to look at the current // assembly and find any and all classes that implement IWindsorInstaller. Once you've done that, // call the "Install" method on each of them." In our implementation, we have // one installer for each dependent assembly. return(container.Install(FromAssembly.This())); }
/// <summary>配置默认的Castle容器 /// <remarks>默认使用XmlInterpreter初始化</remarks> /// </summary> /// <param name="configuration"></param> /// <param name="func">执行额外的配置</param> /// <returns></returns> public static Configuration Castle(this Configuration configuration, Action<WindsorResolver> func) { var container = new WindsorContainer(); //从配置文件初始化 container.Install(new ConfigurationInstaller(new XmlInterpreter())); var resolver = new WindsorResolver(container); //设置解释器实例 configuration.Resolver(resolver); //强制注册Log4Net日志工厂+增加注入运行时变量 20111130 resolver.Container.Log4NetLoggerFactory( () => configuration.RuntimeProperties(Configuration.RuntimeProperties_Environment) , () => configuration.RuntimeProperties(Configuration.RuntimeProperties_Environment_Error)); //强制设置Common.Logging使用Log4Net实现且使用外部配置的log4net实例 EXTERNAL Common.Logging.LogManager.Adapter = new Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter(new NameValueCollection() { { "configType", "EXTERNAL" } }); //记录启动信息 var log = DependencyResolver .Resolve<ILoggerFactory>() .Create(typeof(ConfigurationExtensions)); log.Info("不启用NamingSubSystem=NamingSubsystemForDefaultComponent,Castle升级至3.0后无需此子系统"); log.Info("强制使用Log4Net日志工厂"); log.Info("强制设置Common.Logging使用Common.Logging.Log4Net实现"); log.Debug("来自Configuration的在日志组件未初始化前的调试信息:\n" + configuration.PopMessages()); //额外的容器配置 func(resolver); return configuration; }
public BusinessLogicSegment() { this.container = new WindsorContainer(); container.Install(new Installer()); this.util = this.container.Resolve <IUtil>(); this.blSentence = this.container.Resolve <IBusinessLogicSentence>(); }
public void StartableComponentShouldNotStartIfExceptionThrownByInstaller() { UsesIEmptyService.instancesCreated = 0; using (var container = new WindsorContainer()) { container.AddFacility<StartableFacility>(f => f.DeferredStart()); Assert.Throws<NotImplementedException>( () => container.Install(new ActionBasedInstaller(c => c.Register(Component.For<UsesIEmptyService>().Start())), new ActionBasedInstaller(c => c.Register(Component.For<IEmptyService>().ImplementedBy<EmptyServiceA>())), new ActionBasedInstaller(c => { throw new NotImplementedException(); }))); // In this scenario, I've registered IDependencyOfStartableComponent // before the ExceptionThrowingInstaller gets a chance to gum up the works // I would expect that the "deferred start" code NOT run here, // and the StartableComponent remain un-instantiated. // However, Castle is creating the StartableComponent anyway // and then allows the NotImplementedException to bubble out. // Presumably, this is due to the "deferred start" mechanism // being implemented by a using() block or something similar // via OptimizeDependencyResolutionDisposable.Dispose() Assert.AreEqual(0, UsesIEmptyService.instancesCreated); } }
private void InitializeWindsor() { _windsorContainer = new WindsorContainer(); _windsorContainer.Install(FromAssembly.Containing <CoffeeShopDependencyInstaller>()); ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_windsorContainer.Kernel)); }
static IWindsorContainer ConfigureIoC() { var container = new WindsorContainer(); container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true)); container.Install(Configuration.FromAppConfig(), FromAssembly.This(), FromAssembly.Containing<GuestBookXmlProvider>()); return container; }
public static IWindsorContainer Regist() { var container = new WindsorContainer(); container.Install(FromAssembly.This()); return(container); }