public void Init(IEnumerable<Type> dataMigrations) { var builder = new ContainerBuilder(); _folders = new StubFolders(); var contentDefinitionManager = new Mock<IContentDefinitionManager>().Object; builder.RegisterInstance(new ShellSettings { DataTablePrefix = "TEST_"}); builder.RegisterType<SqlServerDataServicesProvider>().As<IDataServicesProvider>(); builder.RegisterType<DataServicesProviderFactory>().As<IDataServicesProviderFactory>(); builder.RegisterType<NullInterpreter>().As<IDataMigrationInterpreter>(); builder.RegisterInstance(_folders).As<IExtensionFolders>(); builder.RegisterInstance(contentDefinitionManager).As<IContentDefinitionManager>(); builder.RegisterType<ExtensionManager>().As<IExtensionManager>(); builder.RegisterType<DataMigrationManager>().As<IDataMigrationManager>(); builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>(); builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>(); _session = _sessionFactory.OpenSession(); builder.RegisterInstance(new DefaultContentManagerTests.TestSessionLocator(_session)).As<ISessionLocator>().As<ITransactionManager>(); foreach(var type in dataMigrations) { builder.RegisterType(type).As<IDataMigration>(); } _container = builder.Build(); _container.Resolve<IExtensionManager>(); _dataMigrationManager = _container.Resolve<IDataMigrationManager>(); _repository = _container.Resolve<IRepository<DataMigrationRecord>>(); _transactionManager = _container.Resolve<ITransactionManager>(); InitDb(); }
private static void SetupExtensibility(Autofac.ContainerBuilder builder, bool withAspects) { var dynamicProxy = new CastleDynamicProxyProvider(); var aopRepository = new AspectRepository(dynamicProxy); var assemblies = NGS.Utility.AssemblyScanner.GetAssemblies().Where(it => it.FullName.StartsWith("NGS.")); builder.RegisterInstance(new PluginsConfiguration { Assemblies = assemblies }); builder.RegisterType <SystemInitialization>(); builder.RegisterType <AutofacObjectFactory>().As <IObjectFactory>().SingleInstance(); builder.RegisterType <AutofacMefProvider>().As <IExtensibilityProvider>().SingleInstance(); builder.RegisterGeneric(typeof(PluginRepository <>)).As(typeof(IPluginRepository <>)).SingleInstance(); builder.RegisterInstance(aopRepository).As <IAspectRegistrator, IAspectComposer, IInterceptorRegistrator>(); builder.RegisterInstance(dynamicProxy).As <IMixinProvider, IDynamicProxyProvider>(); if (withAspects) { var autofacModules = from type in NGS.Utility.AssemblyScanner.GetAllTypes() where type.IsPublic && typeof(Autofac.Module).IsAssignableFrom(type) && type.GetConstructor(new Type[0]) != null select type; foreach (var m in autofacModules) { builder.RegisterModule((Autofac.Module)Activator.CreateInstance(m)); } builder.RegisterModule(new AspectsModule(aopRepository)); } }
public static IContainer Instance() { if(_instance != null) return _instance; var builder = new ContainerBuilder(); var documentStore = new DocumentStore { ConnectionStringName="MessageMonitor" }; documentStore.Initialize(); //documentStore.DatabaseCommands.EnsureDatabaseExists(Database_Name); // documentStore.DefaultDatabase = Database_Name; Raven.Client.Indexes.IndexCreation.CreateIndexes(typeof(Group_Result_Index).Assembly, documentStore); builder.RegisterInstance(documentStore).As<IDocumentStore>(); builder.Register<IDocumentSession>(f => f.Resolve<IDocumentStore>().OpenSession()); var es = WireupEventStore(); builder.RegisterInstance(es).As<IStoreEvents>(); builder.RegisterType<NServiceBus_Audit_Handler>(); _instance = builder.Build(); return _instance; }
static void Main(string[] args) { var env = new ApplicationEnvironment(); var bootupConfigurationProvider = new BootupConfigurationProvider(env); Autofac.ContainerBuilder cb = new Autofac.ContainerBuilder(); cb.RegisterInstance <IEnvironment>(env); cb.RegisterInstance(bootupConfigurationProvider).As <IBootupConfigurationProvider>(); cb.RegisterModule <Teleware.Foundation.Core.Module>(); cb.RegisterModule <Teleware.Foundation.Configuration.Module>(); cb.RegisterModule <Teleware.Foundation.Diagnostics.Loggers.NLog.Module>(); cb.RegisterModule <Teleware.Foundation.Data.Memory.Module>(); //cb.RegisterModule<Teleware.Foundation.Data.EntityFramework.Module>(); //cb.RegisterModule<Teleware.Foundation.Data.EntityFramework.Oracle.Module>(); var container = cb.Build(); using (var lt = container.BeginLifetimeScope()) { while (true) { var db = lt.Resolve <IOptions <DatabaseOptions> >(); Console.WriteLine(db.Value.ConnectionStrings.First().ToString()); Thread.Sleep(1000); } } }
public void Init() { if (Directory.Exists(_basePath)) { Directory.Delete(_basePath, true); } Directory.CreateDirectory(_basePath); _appDataFolder = AppDataFolderTests.CreateAppDataFolder(_basePath); _webDownloader = new Mock<IWebDownloader>(); _orchardServices = new StubOrchardServices(); ((StubWorkContextAccessor.WorkContextImpl.StubSite) _orchardServices.WorkContext.CurrentSite).BaseUrl = "http://orchardproject.net"; _settings = new WarmupSettingsPart { Record = new WarmupSettingsPartRecord() }; _orchardServices.WorkContext.CurrentSite.ContentItem.Weld(_settings); var builder = new ContainerBuilder(); builder.RegisterInstance(_appDataFolder).As<IAppDataFolder>(); builder.RegisterInstance(_orchardServices).As<IOrchardServices>(); builder.RegisterType<DefaultLockFileManager>().As<ILockFileManager>(); builder.RegisterType<WarmupUpdater>().As<IWarmupUpdater>(); builder.RegisterType<StubClock>().As<IClock>(); builder.RegisterType<WarmupReportManager>().As<IWarmupReportManager>(); builder.RegisterInstance(new ShellSettings { Name = "Default" }).As<ShellSettings>(); builder.RegisterInstance(_clock = new StubClock()).As<IClock>(); builder.RegisterInstance(_webDownloader.Object).As<IWebDownloader>(); _container = builder.Build(); _lockFileManager = _container.Resolve<ILockFileManager>(); _warmupUpdater = _container.Resolve<IWarmupUpdater>(); _reportManager = _container.Resolve<IWarmupReportManager>(); _warmupFilename = _appDataFolder.Combine(TenantFolder, "warmup.txt"); _lockFilename = _appDataFolder.Combine(TenantFolder, "warmup.txt.lock"); }
public override void Register(ContainerBuilder builder) { var testVirtualPathProvider = new StylesheetBindingStrategyTests.TestVirtualPathProvider(); builder.RegisterInstance(new ShellSettings { Name = "Default" }); _folders = new ExtensionManagerTests.StubFolders(); _packagesInRepository = new ModuleStepTest.StubPackagingSourceManager(); _packageManager = new ModuleStepTest.StubPackageManager(); builder.RegisterInstance(_folders).As<IExtensionFolders>(); builder.RegisterType<RecipeExecutionLogger>().AsSelf(); builder.RegisterType<ExtensionManager>().As<IExtensionManager>(); builder.RegisterType<FeatureManager>().As<IFeatureManager>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>(); builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>(); builder.RegisterType<ShellDescriptorManager>().As<IShellDescriptorManager>().SingleInstance(); builder.RegisterType<ModuleStepTest.StubDataMigrationManager>().As<IDataMigrationManager>(); builder.RegisterInstance(_packagesInRepository).As<IPackagingSourceManager>(); builder.RegisterInstance(_packageManager).As<IPackageManager>(); builder.RegisterType<ShellStateManager>().As<IShellStateManager>().SingleInstance(); builder.RegisterInstance(testVirtualPathProvider).As<IVirtualPathProvider>(); builder.RegisterType<StubEventBus>().As<IEventBus>().SingleInstance(); builder.RegisterType<ThemeService>().As<IThemeService>(); builder.RegisterType<StubOrchardServices>().As<IOrchardServices>(); builder.RegisterType<StubSiteThemeService>().As<ISiteThemeService>(); builder.RegisterType<ThemeStep>(); builder.RegisterSource(new EventsRegistrationSource()); }
public void Init() { var builder = new ContainerBuilder(); builder.RegisterType<ImportExportService>().As<IImportExportService>(); builder.RegisterType<StubShellDescriptorManager>().As<IShellDescriptorManager>(); builder.RegisterType<RecipeManager>().As<IRecipeManager>(); builder.RegisterType<RecipeHarvester>().As<IRecipeHarvester>(); builder.RegisterType<RecipeStepExecutor>().As<IRecipeStepExecutor>(); builder.RegisterType<StubStepQueue>().As<IRecipeStepQueue>().InstancePerLifetimeScope(); builder.RegisterType<StubRecipeJournal>().As<IRecipeJournal>(); builder.RegisterType<StubRecipeScheduler>().As<IRecipeScheduler>(); builder.RegisterType<ExtensionManager>().As<IExtensionManager>(); builder.RegisterType<StubAppDataFolder>().As<IAppDataFolder>(); builder.RegisterType<StubClock>().As<IClock>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<ExtensionManagerTests.StubLoaders>().As<IExtensionLoader>(); builder.RegisterType<RecipeParser>().As<IRecipeParser>(); builder.RegisterType<StubWebSiteFolder>().As<IWebSiteFolder>(); builder.RegisterType<CustomRecipeHandler>().As<IRecipeHandler>(); builder.RegisterType<DefaultContentManager>().As<IContentManager>(); builder.RegisterType<ContentDefinitionManager>().As<IContentDefinitionManager>(); builder.RegisterType<ContentDefinitionWriter>().As<IContentDefinitionWriter>(); builder.RegisterType<StubOrchardServices>().As<IOrchardServices>(); builder.RegisterType<StubAppDataFolder>().As<IAppDataFolder>(); builder.RegisterType<Signals>().As<ISignals>(); builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)); builder.RegisterInstance(new Mock<ISettingsFormatter>().Object); _session = _sessionFactory.OpenSession(); builder.RegisterInstance(new DefaultContentManagerTests.TestSessionLocator(_session)).As<ISessionLocator>(); _container = builder.Build(); _importExportService = _container.Resolve<IImportExportService>(); }
public void Init() { var builder = new ContainerBuilder(); builder.RegisterType<NServiceBusCommitDispatcher>() .As<NServiceBusCommitDispatcher>() .AsImplementedInterfaces() .SingleInstance(); builder.RegisterType<SagaEventStoreRepository>().AsImplementedInterfaces(); builder.RegisterType<EventStoreRepository>().AsImplementedInterfaces(); builder.RegisterType<AggregateFactory>().AsImplementedInterfaces(); builder.RegisterType<ConflictDetector>().AsImplementedInterfaces(); var documentStore = BuildRavenDocumentStore(); var eventStore = InitializeEventSourcing(); builder.RegisterInstance(documentStore); builder.RegisterInstance(eventStore); Container = builder.Build(); NServiceBus .SetLoggingLibrary.Log4Net(log4net.Config.XmlConfigurator.Configure); NServiceBus .Configure.With().AutofacBuilder(Container) .MsmqSubscriptionStorage() .XmlSerializer(); }
private static void SetupDependencies() { IContainer container = null; var containerBuilder = new ContainerBuilder(); //containerBuilder.RegisterModule<ApplicationServicesModule>(); //containerBuilder.RegisterType<NsbEventBus>().As<IEventBus>(); containerBuilder.RegisterType<RavenDBEventStore>().As<IEventStore>(); containerBuilder.RegisterInstance<ICommandService>(InitializeCommandService()); containerBuilder.RegisterInstance<IEventBus>(InitializeEventBus()); //InitializeNServiceBus(container); containerBuilder.Register(x => container); // var config = new AutofacConfiguration(x => // { // var eventBus = InitializeEventBus(); // var eventStore = InitializeEventStore(); // x.For{IEventBus}().Use(eventBus); // x.For{IEventStore}().Use(eventStore); // x.For{IUnitOfWorkFactory}().Use{UnitOfWorkFactory}(); // } //); container = containerBuilder.Build(); AutofacConfiguration config = new AutofacConfiguration(container); // I believe this is a single call to configure inject all component dependencies // e.g. NcqrsEnvironment.SetDefault<IEventBus>( InitializeEventBus() ); NcqrsEnvironment.Configure(config); }
public static IContainer Initialize() { Logger.Info(typeof (ContainerConfig), "Initializing container..."); ContainerBuilder builder = new ContainerBuilder(); ConfigFileConfigurationProvider configurationProvider = new ConfigFileConfigurationProvider(); builder.RegisterInstance(configurationProvider.Service).As<IServiceConfiguration>(); builder.RegisterInstance(configurationProvider.Repository).As<IApplicationRepositoryConfiguration>(); builder.RegisterInstance(configurationProvider.Authentication).As<IAuthenticationConfiguration>(); builder.RegisterType<FileSystemApplicationRepository>().As<IApplicationRepository>(); builder.RegisterType<SystemDateTimeFactory>().As<IDateTimeFactory>(); // register API controllers builder.RegisterApiControllers(typeof (PackagesApiController).Assembly); builder.RegisterControllers(typeof (HomeController).Assembly); // build container Container = Dependency.Build(builder); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(Container); DependencyResolver.SetResolver(new AutofacDependencyResolver(Container)); Logger.Info(typeof (ContainerConfig), "Container initialized"); return (Container); }
protected override void Load(ContainerBuilder builder) { #region mock IPostRepository Mock<IPostRepository> mockPost = new Mock<IPostRepository>(); var posts = new List<Post>() { new Post() {Id = 1, Title = "first blog", Published = DateTime.Now.AddDays(-1)}, new Post() {Id = 2, Title = "second blog", Published = DateTime.Now.AddDays(-2)}, new Post() {Id = 3, Title = "third blog", Published = DateTime.Now.AddDays(-3)}, }; mockPost.Setup(m => m.GetAll()).Returns(posts.AsQueryable()); mockPost.Setup(m => m.Get(It.IsAny<int>())).Returns(posts.SingleOrDefault(p => p.Id == 1)); builder.RegisterInstance(mockPost.Object).As<IPostRepository>().SingleInstance(); #endregion #region mock IUserRepository Mock<IUserRepository> mockUser = new Mock<IUserRepository>(); var users = new List<User> { new User() {Id = 1, Name = "sa", Email = "*****@*****.**", Username = "******", Password = "******"}, //new User() // { // Id = 2, // Name = "admin", // Email = "*****@*****.**", // Username = "******", // Password = "******" // } }; mockUser.Setup(m => m.GetAll()).Returns(users.AsQueryable()); builder.RegisterInstance(mockUser.Object).As<IUserRepository>().SingleInstance(); #endregion }
public void Init() { _users = new List<UserEntity>(); for (var ndx = 0; ndx < 10; ++ndx) { var postfix = ndx.ToString(); var user = new UserEntity { UserEntityId = ndx + 1, DateRegistered = ServerTime.Now, UserName = "******" + postfix, Email = String.Format("user.{0}@test.com", ndx) }; _users.Add(user); } Mapper.CreateMap<UserEntity, User>() .ForMember(p => p.Id, opt => opt.MapFrom(src => src.UserEntityId)) .IgnoreAllNonExisting(); var builder = new ContainerBuilder(); builder.RegisterType<QueryBuilder>().As<IQueryBuilder>(); var entitiesRepo = new Repository<UserEntity>(_users); var usersRepo = new Repository<User>(_users.Select(p => p.MapTo<User>())); builder.RegisterInstance(entitiesRepo).As<IRepository<UserEntity>>().SingleInstance(); builder.RegisterInstance(usersRepo).As<IRepository<User>>().SingleInstance(); var container = builder.Build(); var resolver = new AutofacDependencyResolver(container); DependencyResolver.SetResolver(resolver); }
protected override void Load(ContainerBuilder builder) { builder.RegisterType<AutofacDependencyResolver>().As<IDependencyResolver>().SingleInstance(); builder.RegisterInstance(GlobalFilters.Filters).As<GlobalFilterCollection>().SingleInstance(); builder.RegisterInstance(RouteTable.Routes).As<RouteCollection>().SingleInstance(); builder.RegisterFilterProvider(); }
protected override void Load(ContainerBuilder builder) { #if MOBILE builder.RegisterType<UiContext>().AsImplementedInterfaces(); builder.RegisterInstance(new MobileService(new UiContext())).AsImplementedInterfaces(); builder.RegisterType<VmPageMappings>().AsImplementedInterfaces(); #else builder.RegisterInstance(new MobileService()).AsImplementedInterfaces(); #endif builder.RegisterType<MessageBox>().AsImplementedInterfaces(); builder.RegisterType<AzureStorageService>().AsImplementedInterfaces(); builder.RegisterType<AppSettings>().AsImplementedInterfaces(); builder.RegisterType<Logger>().AsImplementedInterfaces(); builder.RegisterType<PhotoChooser>().AsImplementedInterfaces(); builder.RegisterType<MvxJsonConverter>().AsImplementedInterfaces(); #if NETFX_CORE builder.RegisterType<ShareManager>().AsImplementedInterfaces(); builder.RegisterType<SecondaryPinner>().AsImplementedInterfaces(); builder.RegisterAssemblyTypes(typeof(ViewModelBase).GetTypeInfo().Assembly) .Where(t => t.GetTypeInfo().IsSubclassOf(typeof(ViewModelBase))); builder.RegisterAssemblyTypes(typeof(PollImageViewModelBase).GetTypeInfo().Assembly) .Where(t => t.GetTypeInfo().IsSubclassOf(typeof(PollImageViewModelBase))); #else builder.RegisterType<UiContext>().AsImplementedInterfaces(); builder.RegisterAssemblyTypes(typeof(ViewModelBase).Assembly) .Where(t => t.IsSubclassOf(typeof(ViewModelBase))); builder.RegisterAssemblyTypes(typeof(PollImageViewModelBase).Assembly) .Where(t => t.IsSubclassOf(typeof(PollImageViewModelBase))); #endif }
/// <summary> /// Configuration routine of the autofac container. /// </summary> /// <param name="eventBus">The event bus.</param> /// <param name="hoardeManager">The hoarde manager.</param> /// <param name="configurationManager">The host's configuration manager.</param> public static void Configure(IEventBus eventBus, ServiceModel.IHoardeManager hoardeManager, INutConfiguration configurationManager) { var builder = new ContainerBuilder(); builder.RegisterInstance(eventBus); builder.RegisterInstance(hoardeManager); builder.RegisterInstance(configurationManager); builder.RegisterType<ServiceModel.ServicesManager>().AsImplementedInterfaces().SingleInstance(); builder.RegisterType<ServiceModel.PollingClientCollection>().AsSelf().SingleInstance(); builder.RegisterType<ServiceModel.RegisteredPackagesPollingClient>().AsSelf().SingleInstance(); builder.RegisterType<ServiceModel.ReleasesPollingClient>(); builder.RegisterType<ConfigurationManagement.DbConfigurationSettings>(); // we will apply most of the configuration in one or more assembly modules. builder.RegisterAssemblyModules(typeof(AutofacConfig).Assembly); switch (configurationManager.Mode) { case ExecutionMode.Development: builder.RegisterType<Repositories.OnDisk.OnDiskPackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope(); break; case ExecutionMode.Production: builder.RegisterType<Repositories.SQLiteRepositories.PackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope(); break; default: builder.RegisterType<Repositories.SQLiteRepositories.PackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope(); _log.WarnFormat("Unknown execution mode '{mode}'. Registered Sqlite Repository.", configurationManager.Mode); break; } _container = builder.Build(); }
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { var builder = new ContainerBuilder(); //register umbracocontext as a factory builder.Register(c => UmbracoContext.Current).AsSelf(); //add all the controllers from the assembly builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly()); //getting null pointer exception in the backend of umbraco if I don't load this one builder.RegisterApiControllers(typeof(Umbraco.Web.Trees.ApplicationTreeController).Assembly); //add custom class to the container as transient instance builder.RegisterType<FriendService>().As<IFriendService>(); //se if we can just pass the instances to the builder, works and not needed cause of the umbracocontext, but gives us more control builder.RegisterInstance(UmbracoContext.Current.Application.Services.ContentService); builder.RegisterInstance(UmbracoContext.Current.Application.Services.MemberService); builder.RegisterInstance(UmbracoContext.Current.Application.Services.RelationService); builder.RegisterInstance(UmbracoContext.Current.Application.Services.MediaService); builder.RegisterInstance(UmbracoContext.Current.Application.DatabaseContext.Database).As<Umbraco.Core.Persistence.Database>(); //register the myhelper class should be a interface etc. builder.RegisterType<MyHelper>().As<IMyHelper>(); var container = builder.Build(); //setup the webapi dependency resolver to use autofac System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); base.ApplicationStarted(umbracoApplication, applicationContext); }
public void Init() { _contentDefinitionManager = new Mock<IContentDefinitionManager>(); var builder = new ContainerBuilder(); builder.RegisterType<DefaultContentManager>().As<IContentManager>(); builder.RegisterType<DefaultContentManagerSession>().As<IContentManagerSession>(); builder.RegisterInstance(_contentDefinitionManager.Object); builder.RegisterInstance(new Mock<IContentDisplay>().Object); builder.RegisterType<AlphaPartHandler>().As<IContentHandler>(); builder.RegisterType<BetaPartHandler>().As<IContentHandler>(); builder.RegisterType<GammaPartHandler>().As<IContentHandler>(); builder.RegisterType<DeltaPartHandler>().As<IContentHandler>(); builder.RegisterType<EpsilonPartHandler>().As<IContentHandler>(); builder.RegisterType<FlavoredPartHandler>().As<IContentHandler>(); builder.RegisterType<StyledHandler>().As<IContentHandler>(); builder.RegisterType<DefaultShapeTableManager>().As<IShapeTableManager>(); builder.RegisterType<ShapeTableLocator>().As<IShapeTableLocator>(); builder.RegisterType<DefaultShapeFactory>().As<IShapeFactory>(); builder.RegisterType<DefaultContentDisplay>().As<IContentDisplay>(); builder.RegisterType<StubExtensionManager>().As<IExtensionManager>(); builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)); _session = _sessionFactory.OpenSession(); builder.RegisterInstance(new TestSessionLocator(_session)).As<ISessionLocator>(); _container = builder.Build(); _manager = _container.Resolve<IContentManager>(); }
public override void RegisterComponents(ContainerBuilder builder) { base.RegisterComponents(builder); builder.RegisterInstance(this).As<NuGetApiService>(); var config = ConfigureWebApi(); builder.RegisterInstance(config).AsSelf(); builder .RegisterApiControllers(GetControllerAssemblies().ToArray()) .OnActivated(e => { var nugetController = e.Instance as NuGetApiController; if (nugetController != null) { nugetController.Host = Host; nugetController.Service = this; nugetController.Container = Container; } }) .InstancePerApiRequest(); builder.RegisterWebApiFilterProvider(config); builder.RegisterWebApiModelBinderProvider(); }
public void WithParameter_Integration() { var builder = new ContainerBuilder(); builder.RegisterInstance<string>("example_value_one") .Keyed<string>("key_one") .SingleInstance(); builder.RegisterInstance<string>("example_value_two") .Keyed<string>("key_two") .SingleInstance(); builder.RegisterType<ExampleType>() .WithParameter("value1", c => c.ResolveKeyed<string>("key_one")) .WithParameter("value2", c => c.ResolveKeyed<string>("key_two")) .SingleInstance(); using (var container = builder.Build()) { var example = container.ResolveOptional<ExampleType>(); Assert.That(example, Is.Not.Null); Assert.That(example.Value1, Is.EqualTo("example_value_one")); Assert.That(example.Value2, Is.EqualTo("example_value_two")); } }
/// <summary> /// Configures a <see cref="NDomain.IoC.IDependencyResolver"/> to use Autofac /// based on the <paramref name="container"/>. Useful to resolve application message handlers /// that depend on other components external to NDomain. /// The application's Autofac container will also get updated with registries for NDomain's components. /// </summary> /// <param name="b">configurator instance</param> /// <param name="container">application's Autofac container</param> /// <returns>Current configurator instance, to be used in a fluent manner.</returns> public static IoCConfigurator WithAutofac(this IoCConfigurator b, IContainer container) { b.Resolver = new AutofacDependencyResolver(container.BeginLifetimeScope()); b.Configured += context => { var builder = new ContainerBuilder(); builder.RegisterInstance(context); builder.RegisterInstance(context.CommandBus); builder.RegisterInstance(context.EventBus); builder.RegisterInstance(context.EventStore).As<IEventStore>(); builder.RegisterGeneric(typeof(AggregateRepository<>)) .As(typeof(IAggregateRepository<>)).SingleInstance(); // usually command/event handlers foreach (var knownType in b.KnownTypes) { builder.RegisterType(knownType) .AsSelf() .PreserveExistingDefaults(); } builder.Update(container); }; return b; }
public void Init() { var builder = new ContainerBuilder(); //builder.RegisterModule(new ImplicitCollectionSupportModule()); builder.RegisterType<MembershipService>().As<IMembershipService>(); builder.RegisterType<DefaultContentQuery>().As<IContentQuery>(); builder.RegisterType<DefaultContentManager>().As<IContentManager>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<Signals>().As<ISignals>(); builder.RegisterType(typeof(SettingsFormatter)).As<ISettingsFormatter>(); builder.RegisterType<ContentDefinitionManager>().As<IContentDefinitionManager>(); builder.RegisterType<DefaultContentManagerSession>().As<IContentManagerSession>(); builder.RegisterInstance(new ShellSettings { Name = ShellSettings.DefaultName, DataProvider = "SqlCe" }); builder.RegisterType<UserPartHandler>().As<IContentHandler>(); builder.RegisterType<StubWorkContextAccessor>().As<IWorkContextAccessor>(); builder.RegisterType<OrchardServices>().As<IOrchardServices>(); builder.RegisterAutoMocking(MockBehavior.Loose); builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)); builder.RegisterType<DefaultShapeTableManager>().As<IShapeTableManager>(); builder.RegisterType<DefaultShapeFactory>().As<IShapeFactory>(); builder.RegisterType<StubExtensionManager>().As<IExtensionManager>(); builder.RegisterInstance(new Mock<IPageClassBuilder>().Object); builder.RegisterType<DefaultContentDisplay>().As<IContentDisplay>(); builder.RegisterType<InfosetHandler>().As<IContentHandler>(); _session = _sessionFactory.OpenSession(); builder.RegisterInstance(new TestTransactionManager(_session)).As<ITransactionManager>(); _container = builder.Build(); _membershipService = _container.Resolve<IMembershipService>(); }
public void Setup() { _databaseFileName = Path.GetTempFileName(); _sessionFactory = DataUtility.CreateSessionFactory(_databaseFileName); _tempFolder = Path.GetTempFileName(); File.Delete(_tempFolder); var appDataFolder = AppDataFolderTests.CreateAppDataFolder(_tempFolder); var builder = new ContainerBuilder(); _session = _sessionFactory.OpenSession(); builder.RegisterInstance(appDataFolder).As<IAppDataFolder>(); builder.RegisterType<SqlCeDataServicesProvider>().As<IDataServicesProvider>(); builder.RegisterType<DataServicesProviderFactory>().As<IDataServicesProviderFactory>(); builder.RegisterType<StubReportsCoordinator>().As<IReportsCoordinator>(); builder.RegisterType<DefaultDataMigrationInterpreter>().As<IDataMigrationInterpreter>(); builder.RegisterType<SqlCeCommandInterpreter>().As<ICommandInterpreter>(); builder.RegisterType<SessionConfigurationCache>().As<ISessionConfigurationCache>(); builder.RegisterType<SessionFactoryHolder>().As<ISessionFactoryHolder>(); builder.RegisterType<DefaultDatabaseCacheConfiguration>().As<IDatabaseCacheConfiguration>(); builder.RegisterType<StubHostEnvironment>().As<IHostEnvironment>(); builder.RegisterInstance(new TestTransactionManager(_session)).As<ITransactionManager>(); builder.RegisterInstance(new ShellBlueprint { Records = Enumerable.Empty<RecordBlueprint>() }).As<ShellBlueprint>(); builder.RegisterInstance(new ShellSettings { Name = "temp", DataProvider = "SqlCe", DataTablePrefix = "TEST" }).As<ShellSettings>(); builder.RegisterModule(new DataModule()); _container = builder.Build(); _interpreter = _container.Resolve<IDataMigrationInterpreter>() as DefaultDataMigrationInterpreter; _schemaBuilder = new SchemaBuilder(_interpreter); }
public async Task RouteAnUnknownIntentToTheDefaultHandler() { var containerBuilder = new Autofac.ContainerBuilder(); var httpResponseMessage = new Mock <IHttpResponseMessage>(); var httpResponseTask = Task.Run(() => httpResponseMessage.Object); httpResponseMessage.SetupGet(m => m.Content).Returns(_routesJson); var httpProxy = new Mock <IHttpProxy>(); httpProxy.Setup(p => p.GetAsync(It.IsAny <string>(), It.IsAny <IEnumerable <KeyValuePair <string, string> > >())).Returns(httpResponseTask); containerBuilder.RegisterInstance <IHttpProxy>(httpProxy.Object); var cmdProcessor = new Mock <ICommandProcessor>(MockBehavior.Loose); containerBuilder.RegisterInstance <ICommandProcessor>(cmdProcessor.Object); var serviceProvider = new AutofacServiceProvider(containerBuilder.Build()); var request = new UserRequestBuilder().Random().Build(); var target = new DataServiceRouter.Engine(serviceProvider, string.Empty); var actual = await target.HandleRequestAsync(request); cmdProcessor.Verify(p => p.ProcessAsync("abcdefg", It.IsAny <UserRequest>()), Times.Once); }
public void Init() { _tempFolderName = Path.GetTempFileName(); File.Delete(_tempFolderName); var assembly = GetType().Assembly; foreach (var name in assembly.GetManifestResourceNames()) { if (name.StartsWith(DataPrefix)) { string text; using (var stream = assembly.GetManifestResourceStream(name)) { using (var reader = new StreamReader(stream)) text = reader.ReadToEnd(); } // Pro filtering var relativePath = name .Substring(DataPrefix.Length) .Replace(".txt", ":txt") .Replace(".recipe.xml", ":recipe:xml") .Replace('.', Path.DirectorySeparatorChar) .Replace(":txt", ".txt") .Replace(":recipe:xml", ".recipe.xml"); var targetPath = Path.Combine(_tempFolderName, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); using (var stream = new FileStream(targetPath, FileMode.Create)) { using (var writer = new StreamWriter(stream)) { writer.Write(text); } } } } var builder = new ContainerBuilder(); var harvester = new ExtensionHarvester(new StubCacheManager(), new StubWebSiteFolder(), new Mock<ICriticalErrorProvider>().Object); _folders = new ModuleFolders(new[] { _tempFolderName }, harvester); builder.RegisterType<RecipeManager>().As<IRecipeManager>(); builder.RegisterType<RecipeHarvester>().As<IRecipeHarvester>(); builder.RegisterType<RecipeStepExecutor>().As<IRecipeStepExecutor>(); builder.RegisterType<StubStepQueue>().As<IRecipeStepQueue>().InstancePerLifetimeScope(); builder.RegisterType<StubRecipeJournal>().As<IRecipeJournal>(); builder.RegisterType<StubRecipeScheduler>().As<IRecipeScheduler>(); builder.RegisterType<ExtensionManager>().As<IExtensionManager>(); builder.RegisterType<StubAppDataFolder>().As<IAppDataFolder>(); builder.RegisterType<StubClock>().As<IClock>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>(); builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>(); builder.RegisterInstance(_folders).As<IExtensionFolders>(); builder.RegisterInstance(new Mock<IRecipeExecuteEventHandler>().Object); builder.RegisterType<Environment.Extensions.ExtensionManagerTests.StubLoaders>().As<IExtensionLoader>(); builder.RegisterType<RecipeParser>().As<IRecipeParser>(); builder.RegisterType<StubWebSiteFolder>().As<IWebSiteFolder>(); builder.RegisterType<CustomRecipeHandler>().As<IRecipeHandler>(); _container = builder.Build(); _recipeManager = _container.Resolve<IRecipeManager>(); _recipeParser = _container.Resolve<IRecipeParser>(); _recipeHarvester = _container.Resolve<IRecipeHarvester>(); }
static int Main(string[] args) { var options = ParseCommandLine(args); if (options == null) { return(1); } var logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.ColoredConsole() .CreateLogger(); var builder = new Autofac.ContainerBuilder(); builder.RegisterType <TestClient>().As <ITestApi>(); builder.RegisterInstance(logger).As <ILogger>(); builder.RegisterInstance(options).As <IProgramOptions>(); builder.RegisterType <TestClient>().AsSelf(); //builder.RegisterType<SignalRClient>().AsSelf(); using (var container = builder.Build()) { Run(container).Wait(); } return(0); }
public void RequestShouldBeDispatchedToAllHandlers() { var thing1 = new StubHandler(); var thing2 = new StubHandler(); var builder = new ContainerBuilder(); //builder.RegisterModule(new ImplicitCollectionSupportModule()); builder.RegisterType<HomeController>(); builder.RegisterType<XmlRpcReader>().As<IMapper<XElement, XRpcMethodCall>>(); builder.RegisterType<XmlRpcWriter>().As<IMapper<XRpcMethodResponse, XElement>>(); builder.RegisterInstance(thing1).As<IXmlRpcHandler>(); builder.RegisterInstance(thing2).As<IXmlRpcHandler>(); var container = builder.Build(); var controller = container.Resolve<HomeController>(); Assert.That(thing1.ProcessCalls, Is.EqualTo(0)); Assert.That(thing2.ProcessCalls, Is.EqualTo(0)); var result = controller.ServiceEndpoint(new XRpcMethodCall()); Assert.That(result, Is.Not.Null); Assert.That(thing1.ProcessCalls, Is.EqualTo(1)); Assert.That(thing2.ProcessCalls, Is.EqualTo(1)); }
public async Task RouteAnKnownIntentToTheProperHandlerUsingAJsonConfigFile() { string intentName = "hijklmnop"; string routeUri = $"http://www.{intentName}.com"; var cmdProcessor = new Mock <ICommandProcessor>(MockBehavior.Loose); var config = new ConfigurationBuilder() .AddJsonFile("routes.json") .Build(); var containerBuilder = new Autofac.ContainerBuilder(); containerBuilder.RegisterInstance <ICommandProcessor>(cmdProcessor.Object); containerBuilder.RegisterInstance <IConfiguration>(config); var serviceProvider = new AutofacServiceProvider(containerBuilder.Build()); var intent = new IntentBuilder().Random().AddName(intentName); var request = new UserRequestBuilder().Random().AddIntent(intent).Build(); var target = new ConfigRouter.Engine(serviceProvider); var actual = await target.HandleRequestAsync(request); cmdProcessor.Verify(p => p.ProcessAsync(routeUri, It.IsAny <UserRequest>()), Times.Once); }
public static IContainer Configure(WsFederationPluginOptions options, InternalConfiguration internalConfig) { if (internalConfig == null) throw new ArgumentNullException("internalConfig"); if (options == null) throw new ArgumentNullException("options"); var factory = options.Factory; factory.Validate(); var builder = new ContainerBuilder(); // mandatory from factory builder.Register(factory.CoreSettings); builder.Register(factory.UserService); builder.Register(factory.RelyingPartyService); builder.Register(factory.WsFederationSettings); // validators builder.RegisterType<SignInValidator>().AsSelf(); // processors builder.RegisterType<SignInResponseGenerator>().AsSelf(); builder.RegisterType<MetadataResponseGenerator>().AsSelf(); // general services builder.RegisterType<CookieMiddlewareTrackingCookieService>().As<ITrackingCookieService>(); builder.RegisterInstance(options).AsSelf(); builder.RegisterInstance(internalConfig).AsSelf(); // load core controller builder.RegisterApiControllers(typeof(WsFederationController).Assembly); return builder.Build(); }
public async Task RouteAnUnknownIntentToTheDefaultHandler() { string defaultRouteUri = $"http://{string.Empty.GetRandom()}"; var cmdProcessor = new Mock <ICommandProcessor>(MockBehavior.Loose); var routes = new RouteCollectionBuilder(defaultRouteUri) .Add(string.Empty.GetRandom(), string.Empty.GetRandom()) .Add(string.Empty.GetRandom(), string.Empty.GetRandom()) .Add(string.Empty.GetRandom(), string.Empty.GetRandom()) .Build().AsJsonString(); var routeCollection = new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("intentRoutes", routes) }; var config = new ConfigurationBuilder().AddInMemoryCollection(routeCollection).Build(); var containerBuilder = new Autofac.ContainerBuilder(); containerBuilder.RegisterInstance <ICommandProcessor>(cmdProcessor.Object); containerBuilder.RegisterInstance <IConfiguration>(config); var serviceProvider = new AutofacServiceProvider(containerBuilder.Build()); var request = new UserRequestBuilder().Random().Build(); var target = new ConfigRouter.Engine(serviceProvider); var actual = await target.HandleRequestAsync(request); cmdProcessor.Verify(p => p.ProcessAsync(defaultRouteUri, It.IsAny <UserRequest>()), Times.Once); }
internal Shell CreateShell(BrowseForRepositoryEvent browseForRepositoryEvent, Arguments arguments) { var builder = new Autofac.ContainerBuilder(); ChorusUIComponentsInjector.Inject(builder, _projectPath, SyncUIFeatures.Advanced); builder.RegisterInstance(browseForRepositoryEvent).As<BrowseForRepositoryEvent>().SingleInstance(); //For now, we like the idea of just using the login name. But //this allows someone to override that in the ini (which would be for all users of this machine, then) builder.Register<IChorusUser>(c => new ChorusUser(c.Resolve<HgRepository>().GetUserNameFromIni(new NullProgress(), System.Environment.UserName))); builder.RegisterType<Shell>(); if(arguments!=null) { builder.RegisterInstance(arguments); Synchronizer.s_testingDoNotPush = arguments.DontPush; //hack, at this point it would take a lot of plumbing //to get this properly to any synchronizer that is created. Can be fixed if/when we go to the //autofac generated factor approach } _container = builder.Build(); var shell= _container.Resolve<Shell>(); var system = new ChorusSystem(_projectPath); system.Init(string.Empty); shell.AddPage("Review", system.WinForms.CreateHistoryPage()); shell.AddPage("Notes", system.WinForms.CreateNotesBrowser()); shell.AddPage("Send/Receive", _container.Resolve<SyncPanel>()); shell.AddPage("Settings", _container.Resolve<SettingsView>()); shell.AddPage("Troubleshooting", _container.Resolve<TroubleshootingView>()); return shell; }
private static void SetupExtensibility(Autofac.ContainerBuilder builder) { var dynamicProxy = new CastleDynamicProxyProvider(); var aopRepository = new AspectRepository(dynamicProxy); var dllPlugins = (from key in ConfigurationManager.AppSettings.AllKeys where key.StartsWith("PluginsPath", StringComparison.OrdinalIgnoreCase) let path = ConfigurationManager.AppSettings[key] let pathRelative = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path) let chosenPath = Directory.Exists(pathRelative) ? pathRelative : path select chosenPath) .ToList(); builder.RegisterInstance(new PluginsConfiguration { Directories = dllPlugins }); builder.RegisterType <SystemInitialization>(); builder.RegisterType <AutofacObjectFactory>().As <IObjectFactory>().SingleInstance(); builder.RegisterType <AutofacMefProvider>().As <IExtensibilityProvider>().SingleInstance(); builder.RegisterGeneric(typeof(PluginRepository <>)).As(typeof(IPluginRepository <>)).SingleInstance(); builder.RegisterInstance(aopRepository).As <IAspectRegistrator, IAspectComposer, IInterceptorRegistrator>(); builder.RegisterInstance(dynamicProxy).As <IMixinProvider, IDynamicProxyProvider>(); if (ConfigurationManager.AppSettings["Revenj.AllowAspects"] == "true") { builder.RegisterModule(new AspectsModule(aopRepository)); } }
public void RegisterTypeRegistration_Default_WithEnumerationParameter() { var itemNames = new string[] { "first", "second", "third" }; var registration = new TypeRegistration<RegisteredServiceConsumer>(() => new RegisteredServiceConsumer(EntLibContainer.ResolvedEnumerable<ISampleService>(itemNames))); registration.IsDefault = true; registration.Lifetime = TypeRegistrationLifetime.Transient; var builder = new ContainerBuilder(); builder.RegisterTypeRegistration(registration); var first = new SampleServiceImpl(); builder.RegisterInstance(first).Named<ISampleService>("first"); var second = new SampleServiceImpl(); builder.RegisterInstance(second).Named<ISampleService>("second"); var third = new SampleServiceImpl(); builder.RegisterInstance(third).Named<ISampleService>("third"); var container = builder.Build(); var resolved = container.Resolve<RegisteredServiceConsumer>(); Assert.IsInstanceOf<IEnumerable<ISampleService>>(resolved.CtorParameter, "The constructor parameter was not the right type."); var services = ((IEnumerable<ISampleService>)resolved.CtorParameter).ToArray(); Assert.AreSame(first, services[0], "The first enumerable service was not resolved properly."); Assert.AreSame(second, services[1], "The second enumerable service was not resolved properly."); Assert.AreSame(third, services[2], "The third enumerable service was not resolved properly."); }
public void Init() { string databaseFileName = Path.GetTempFileName(); IDataServicesProviderFactory dataServicesProviderFactory = new DataServicesProviderFactory(new[] { new Meta<CreateDataServicesProvider>( (dataFolder, connectionString) => new SqlCeDataServicesProvider(dataFolder, connectionString), new Dictionary<string, object> {{"ProviderName", "SqlCe"}}) }); var builder = new ContainerBuilder(); builder.RegisterInstance(new ShellBlueprint()); builder.RegisterInstance(new ShellSettings { Name = ShellSettings.DefaultName, DataTablePrefix = "Test", DataProvider = "SqlCe" }); builder.RegisterInstance(dataServicesProviderFactory).As<IDataServicesProviderFactory>(); builder.RegisterInstance(AppDataFolderTests.CreateAppDataFolder(Path.GetDirectoryName(databaseFileName))).As<IAppDataFolder>(); builder.RegisterType<SqlCeDataServicesProvider>().As<IDataServicesProvider>(); builder.RegisterType<SessionConfigurationCache>().As<ISessionConfigurationCache>(); builder.RegisterType<SessionFactoryHolder>().As<ISessionFactoryHolder>(); builder.RegisterType<CompositionStrategy>().As<ICompositionStrategy>(); builder.RegisterType<ExtensionManager>().As<IExtensionManager>(); builder.RegisterType<SchemaCommandGenerator>().As<ISchemaCommandGenerator>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>(); builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>(); builder.RegisterType<StubHostEnvironment>().As<IHostEnvironment>(); _container = builder.Build(); _extensionManager = _container.Resolve<IExtensionManager>(); _schemaCommandGenerator = _container.Resolve<ISchemaCommandGenerator>(); }
public void Init() { var builder = new ContainerBuilder(); builder.RegisterType<DynamicExtensionLoaderAccessor>().As<DynamicExtensionLoaderAccessor>(); builder.RegisterType<DefaultBuildManager>().As<IBuildManager>(); builder.RegisterType<DefaultAssemblyProbingFolder>().As<IAssemblyProbingFolder>(); builder.RegisterType<StubHostEnvironment>().As<IHostEnvironment>(); builder.RegisterType<StubVirtualPathMonitor>().As<IVirtualPathMonitor>(); builder.RegisterType<StubVirtualPathProvider>().As<IVirtualPathProvider>(); builder.RegisterType<DefaultAssemblyLoader>().As<IAssemblyLoader>(); builder.RegisterType<StubClock>().As<IClock>(); builder.RegisterType<StubAppDataFolder>().As<IAppDataFolder>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterInstance(new ExtensionLocations()); _mockedStubProjectFileParser = new Mock<IProjectFileParser>(); builder.RegisterInstance(_mockedStubProjectFileParser.Object).As<IProjectFileParser>(); builder.RegisterInstance(new StubFileSystem(new StubClock())).As<StubFileSystem>(); _mockedDependenciesFolder = new Mock<IDependenciesFolder>(); builder.RegisterInstance(_mockedDependenciesFolder.Object).As<IDependenciesFolder>(); _container = builder.Build(); }
static void Main() { var memos = new List<Memo> { new Memo { Title = "Release Autofac 1.1", DueAt = new DateTime(2007, 03, 12) }, new Memo { Title = "Update CodeProject Article", DueAt = DateTime.Now }, new Memo { Title = "Release Autofac 3", DueAt = new DateTime(2011, 07, 01) } }; var builder = new ContainerBuilder(); builder.Register(c => new MemoChecker(c.Resolve<IList<Memo>>(), c.Resolve<IMemoDueNotifier>())); builder.RegisterType<PrintingNotifier>().As<IMemoDueNotifier>(); builder.RegisterInstance(memos).As<IList<Memo>>(); builder.RegisterInstance(Console.Out).As<TextWriter>().ExternallyOwned(); using (var container = builder.Build()) { container.Resolve<MemoChecker>().CheckNow(); } Console.WriteLine("Done! Press any key."); Console.ReadKey(); }
protected override void ConfigureContainer(ContainerBuilder builder) { builder.RegisterType<Shell>().AsSelf(); builder.RegisterType<TransitionContentControlRegionAdapter>(); builder.RegisterModule<FileReplicatorModuleConfiguration>(); builder.RegisterInstance(Logger); builder.RegisterInstance(ModuleCatalog); builder.RegisterInstance(Application.Current.Dispatcher); RegisterTypeIfMissing(builder, typeof(IServiceLocator), typeof(CustomAutofacAdapter), true); RegisterTypeIfMissing(builder, typeof(IModuleInitializer), typeof(ModuleInitializer), true); RegisterTypeIfMissing(builder, typeof(IModuleManager), typeof(ModuleManager), true); RegisterTypeIfMissing(builder, typeof(RegionAdapterMappings), typeof(RegionAdapterMappings), true); RegisterTypeIfMissing(builder, typeof(IRegionManager), typeof(RegionManager), true); RegisterTypeIfMissing(builder, typeof(SelectorRegionAdapter), typeof(SelectorRegionAdapter), true); RegisterTypeIfMissing(builder, typeof(ItemsControlRegionAdapter), typeof(ItemsControlRegionAdapter), true); RegisterTypeIfMissing(builder, typeof(ContentControlRegionAdapter), typeof(ContentControlRegionAdapter), true); RegisterTypeIfMissing(builder, typeof(DelayedRegionCreationBehavior), typeof(DelayedRegionCreationBehavior), false); RegisterTypeIfMissing(builder, typeof(BindRegionContextToDependencyObjectBehavior), typeof(BindRegionContextToDependencyObjectBehavior), false); RegisterTypeIfMissing(builder, typeof(AutoPopulateRegionBehavior), typeof(AutoPopulateRegionBehavior), false); RegisterTypeIfMissing(builder, typeof(RegionActiveAwareBehavior), typeof(RegionActiveAwareBehavior), false); RegisterTypeIfMissing(builder, typeof(SyncRegionContextWithHostBehavior), typeof(SyncRegionContextWithHostBehavior), false); RegisterTypeIfMissing(builder, typeof(RegionManagerRegistrationBehavior), typeof(RegionManagerRegistrationBehavior), false); RegisterTypeIfMissing(builder, typeof(RegionMemberLifetimeBehavior), typeof(RegionMemberLifetimeBehavior), false); RegisterTypeIfMissing(builder, typeof(ClearChildViewsRegionBehavior), typeof(ClearChildViewsRegionBehavior), false); RegisterTypeIfMissing(builder, typeof(IEventAggregator), typeof(EventAggregator), true); RegisterTypeIfMissing(builder, typeof(IRegionViewRegistry), typeof(RegionViewRegistry), true); RegisterTypeIfMissing(builder, typeof(IRegionBehaviorFactory), typeof(RegionBehaviorFactory), true); RegisterTypeIfMissing(builder, typeof(IRegionNavigationJournalEntry), typeof(RegionNavigationJournalEntry), false); RegisterTypeIfMissing(builder, typeof(IRegionNavigationJournal), typeof(RegionNavigationJournal), false); RegisterTypeIfMissing(builder, typeof(IRegionNavigationService), typeof(RegionNavigationService), false); RegisterTypeIfMissing(builder, typeof(IRegionNavigationContentLoader), typeof(RegionNavigationContentLoader), true); CreateScriptRuntime(builder); }
public void Configure(IComponentRegistry componentRegistry) { var builder = new ContainerBuilder(); if (_atomicStorageFactory == null) { AtomicIsInMemory(strategyBuilder => { }); } if (_streamingRoot == null) { StreamingIsInFiles(Directory.GetCurrentDirectory()); } if (_tapeStorage == null) { TapeIsInMemory(); } var core = new AtomicRegistrationCore(_atomicStorageFactory); var source = new AtomicRegistrationSource(core); builder.RegisterSource(source); builder.RegisterInstance(new NuclearStorage(_atomicStorageFactory)); builder .Register( c => new AtomicStorageInitialization(new[] {_atomicStorageFactory}, c.Resolve<ISystemObserver>())) .As<IEngineProcess>().SingleInstance(); builder.RegisterInstance(_streamingRoot); builder.RegisterInstance(_tapeStorage); builder.RegisterInstance(new TapeStorageInitilization(new[] {_tapeStorage})).As<IEngineProcess>(); builder.Update(componentRegistry); }
protected override void Load(Autofac.ContainerBuilder builder) { builder.RegisterInstance(_configuration.GetSettings <GeneralSettings>()) .SingleInstance(); builder.RegisterInstance(_configuration.GetSettings <JwtSettings>()) .SingleInstance(); builder.RegisterInstance(_configuration.GetSettings <FinancialModelingPrepSettings>()) .SingleInstance(); builder.RegisterInstance(_configuration.GetSettings <MongoSettings>()) .SingleInstance(); }
/// <summary> /// 注册实例对象 /// 【RegisterInstance】 /// </summary> /// <param name="builder"></param> /// <returns></returns> protected override Autofac.ContainerBuilder RegisterFunc(Autofac.ContainerBuilder builder) { var stuRepository = new StudentRepository(); builder.RegisterInstance(stuRepository).As <IStudentRepository>(); var stuService = new StudentAppService(stuRepository); builder.RegisterInstance(stuService).As <IStudentAppService>(); return(builder); }
private void RegisterConfigSettings(Autofac.ContainerBuilder builder) { builder.RegisterGeneric(typeof(OptionsManager <>)).As(typeof(IOptions <>)).SingleInstance(); builder.RegisterGeneric(typeof(OptionsMonitor <>)).As(typeof(IOptionsMonitor <>)).SingleInstance(); builder.RegisterGeneric(typeof(OptionsSnapshot <>)).As(typeof(IOptionsSnapshot <>)).InstancePerLifetimeScope(); builder.RegisterInstance(_configuration).As <IConfiguration>(); }
private static void RegisterInputProviders(Autofac.ContainerBuilder builder) { builder.RegisterInstance(new TextReaderInputProvider(System.Console.In, System.Console.Out)).As <IInputProvider>(); builder.RegisterType <DemoInputProvider>().As <IInputProvider>(); builder.RegisterType <InputProviderFactory>().AsImplementedInterfaces(); }
private void OwinStartup(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); IDependencyResolver resolver; #if true Unity.IUnityContainer uc = new Unity.UnityContainer(); uc.RegisterInstance(typeof(IPlop), new Plop()); resolver = new UnityResolver(uc); #else Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder(); builder.RegisterApiControllers(typeof(WorkerRole).Assembly); builder.RegisterInstance(new Plop()).As <IPlop>(); Autofac.IContainer container = builder.Build(); app.UseAutofacMiddleware(container); app.UseAutofacWebApi(config); resolver = new AutofacWebApiDependencyResolver(container); #endif config.DependencyResolver = resolver; config.MapHttpAttributeRoutes(); config.EnsureInitialized(); app.UseWebApi(config); }
protected override void Load(Autofac.ContainerBuilder builder) { builder.RegisterType <FaceComparer>() .As <FaceComparer>() .WithProperty("FaceAlignmentModelPath", GetAbsolutePath(Properties.Settings.Default.FaceAlignModelFile)) .WithProperty("FaceAlignClassifierPath", GetAbsolutePath(Properties.Settings.Default.FaceAlignClassifierFile)) .WithProperty("FaceRepositoryPath", GetAbsolutePath(Properties.Settings.Default.FaceRepositoryPath)) .WithProperty("IlluminateReferenceFilePath", GetAbsolutePath(Properties.Settings.Default.IlluminateRefFilePath)) .PropertiesAutowired(); if (EnableFaceComparer) { if (System.IO.Directory.Exists(PersonOfInterestLibraryPath)) { var personRepository = SuspectsRepositoryManager.LoadFrom(PersonOfInterestLibraryPath); builder.RegisterInstance(personRepository.Peoples) .As <IEnumerable <PersonOfInterest> >() .ExternallyOwned(); } } else { builder.Register(c => new PersonOfInterest[0]).SingleInstance(); builder.RegisterType <NullRepositoryFaceComparer>() .As <IRepositoryFaceComparer>(); } }
public IDependencyContainer Build() { _register(_containerBuilder); RegisterModules(); _containerBuilder.RegisterInstance <IDependencyContainer>(this).SingleInstance(); CurrentContainer = _containerBuilder.Build(); return(this); }
protected override void Register(Autofac.ContainerBuilder builder) { _descriptor = new ShellDescriptor { }; _testViewEngine = new TestViewEngine(); _testVirtualPathProvider = new TestVirtualPathProvider { TestViewEngine = _testViewEngine }; builder.Register(ctx => _descriptor); builder.RegisterType <StylesheetBindingStrategy>().As <IShapeTableProvider>(); builder.RegisterInstance(_testViewEngine).As <IShapeTemplateViewEngine>(); builder.RegisterInstance(_testVirtualPathProvider).As <IVirtualPathProvider>(); var extensionManager = new Mock <IExtensionManager>(); builder.Register(ctx => extensionManager); builder.Register(ctx => extensionManager.Object); }
public void ThrowMissingRouteExceptionIfNoDefaultRouteProvided() { var cmdProcessor = new Mock <ICommandProcessor>(MockBehavior.Loose); var config = new ConfigurationBuilder() .AddJsonFile("noDefaultRoute.json") .Build(); var containerBuilder = new Autofac.ContainerBuilder(); containerBuilder.RegisterInstance <ICommandProcessor>(cmdProcessor.Object); containerBuilder.RegisterInstance <IConfiguration>(config); var serviceProvider = new AutofacServiceProvider(containerBuilder.Build()); //var intent = new IntentBuilder().Random().AddName(string.Empty.GetRandom()); //var request = new UserRequestBuilder().Random().AddIntent(intent).Build(); Assert.Throws <MissingRouteException>(() => new ConfigRouter.Engine(serviceProvider)); }
protected override void Load(Autofac.ContainerBuilder builder) { builder.RegisterType <ServiceClientFactory>().As <IServiceClientFactory>().SingleInstance(); builder.RegisterInstance(new ZmqClient(new ZMQ.Context(), "tcp://localhost:8001", "tcp://localhost:8002")) .As <IClient>().SingleInstance(); builder.Register <ICatalogService>(ctx => ctx.Resolve <IServiceClientFactory>().CreateServiceClient <ICatalogService>(15000)); builder.Register <IFooService>(ctx => ctx.Resolve <IServiceClientFactory>().CreateServiceClient <IFooService>(15000)); }
protected override void Load(AF.ContainerBuilder builder) { base.Load(builder); builder .RegisterInstance(new RohamConfigs(new XmlFileSettings(_settingsFilePath))) .As <IPersistenceConfigs>() .As <IRohamConfigs>() .SingleInstance(); }
protected override void Load(Autofac.ContainerBuilder builder) { builder.RegisterInstance(AutoMapperConfig.Initialize()) .SingleInstance(); builder.RegisterModule <CommandModule>(); builder.RegisterModule <RepositoryModule>(); builder.RegisterModule <MongoModule>(); builder.RegisterModule <ServiceModule>(); builder.RegisterModule(new SettingsModule(_configuration)); }
private static void SetupPostgres(Autofac.ContainerBuilder builder, string cs) { builder.RegisterInstance(new NGS.DatabasePersistence.Postgres.ConnectionInfo(cs)); builder.RegisterType <PostgresQueryManager>().As <IDatabaseQueryManager>().InstancePerLifetimeScope(); builder.RegisterType <PostgresDatabaseQuery>().As <IPostgresDatabaseQuery>(); builder.Register(c => c.Resolve <IDatabaseQueryManager>().CreateQuery()).As <IDatabaseQuery>().InstancePerLifetimeScope(); builder.RegisterType <PostgresDatabaseNotification>().As <IDataChangeNotification, IEagerNotification>().SingleInstance(); builder.RegisterType <PostgresObjectFactory>().As <IPostgresConverterRepository, IPostgresConverterFactory>().SingleInstance(); builder.RegisterType <NGS.DatabasePersistence.Postgres.QueryGeneration.QueryExecutor>(); }
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterDependancies(Autofac.ContainerBuilder builder) { builder = builder ?? new ContainerBuilder(); // Register the Web API controllers. builder.RegisterApiControllers(typeof(AutofacConfig).Assembly); var geocahceDirectory = ConfigurationManager.AppSettings["GeoCache"] ?? @".\App_Data\geocache.json"; if (!Path.IsPathRooted(geocahceDirectory)) { geocahceDirectory = Path.Combine(HttpRuntime.AppDomainAppPath, geocahceDirectory); geocahceDirectory = Path.GetFullPath(geocahceDirectory); } builder.RegisterInstance(new Services.Geocoder(geocahceDirectory)); var GedcomFile = ConfigurationManager.AppSettings["GedcomFile"] ?? @".\App_Data\Data.ged"; if (!Path.IsPathRooted(GedcomFile)) { GedcomFile = Path.Combine(HttpRuntime.AppDomainAppPath, GedcomFile); GedcomFile = Path.GetFullPath(GedcomFile); } builder.RegisterInstance(new Gedcom.Net.GedcomDocument(Gedcom.Net.FileDom.FileDocument.Load(GedcomFile))); builder.RegisterType <Services.DataStore>(); // Build the container. var container = builder.Build(); // Create the depenedency resolver. var resolver = new AutofacWebApiDependencyResolver(container); // Configure Web API with the dependency resolver. GlobalConfiguration.Configuration.DependencyResolver = resolver; }
static void Main(string[] args) { /* Dependencies */ string _ConfigPath = AppDomain.CurrentDomain.BaseDirectory + @"\Config"; SysConfigManager.LaserDeskConfigManager ConfigMgr = new SysConfigManager.LaserDeskConfigManager(_ConfigPath); ConfigMgr.Load(); Controller PLC = new Controller(ConfigMgr.SystemConfig.PLCIPaddress, ConfigMgr.SystemConfig.PLCPath, ConfigMgr.SystemConfig.PLCTimeout); var builder = new Autofac.ContainerBuilder(); builder.RegisterType <MyService>(); builder.RegisterType <Controller>(); builder.RegisterType <LaserDeskConfigManager>(); builder.RegisterType <LaserDeskWorker>() .UsingConstructor(typeof(Controller), typeof(SysConfigManager.LaserDeskConfigManager)) .WithParameter("controller", PLC) .WithParameter("config", ConfigMgr); builder.RegisterInstance(PLC); builder.RegisterInstance(ConfigMgr); var container = builder.Build(); HostFactory.Run(hostConfigurator => { hostConfigurator.Service <MyService>(serviceConfigurator => { serviceConfigurator.ConstructUsing(() => container.Resolve <MyService>()); serviceConfigurator.WhenStarted(myService => myService.Start()); serviceConfigurator.WhenStopped(myService => myService.Stop()); }); hostConfigurator.RunAsLocalSystem(); hostConfigurator.SetDisplayName("MyService"); hostConfigurator.SetDescription("MyService using Topshelf"); hostConfigurator.SetServiceName("MyService"); }); }
protected override void Load(AF.ContainerBuilder builder) { var dbUpConfigs = new DbToolPersistenceConfigs() { ShowSql = ShowSql }; (dbUpConfigs as IDbToolConfigsUpdater).SetDatabase(ProviderName, ""); builder .RegisterInstance(dbUpConfigs) .As <IPersistenceConfigs>() .SingleInstance(); }
public void ThrowMissingRouteExceptionIfNoDefaultRouteProvided() { var containerBuilder = new Autofac.ContainerBuilder(); var httpResponseMessage = new Mock <IHttpResponseMessage>(); var httpResponseTask = Task.Run(() => httpResponseMessage.Object); httpResponseMessage.SetupGet(m => m.Content).Returns(_routesWithoutDefaultJson); var httpProxy = new Mock <IHttpProxy>(); httpProxy.Setup(p => p.GetAsync(It.IsAny <string>(), It.IsAny <IEnumerable <KeyValuePair <string, string> > >())).Returns(httpResponseTask); containerBuilder.RegisterInstance <IHttpProxy>(httpProxy.Object); var cmdProcessor = new Mock <ICommandProcessor>(MockBehavior.Loose); containerBuilder.RegisterInstance <ICommandProcessor>(cmdProcessor.Object); var serviceProvider = new AutofacServiceProvider(containerBuilder.Build()); Assert.Throws <MissingRouteException>(() => new DataServiceRouter.Engine(serviceProvider, string.Empty)); }
protected override void Load(Autofac.ContainerBuilder builder) { try { //注册无效的类型 RegisterInvalidTypes(); Assembly[] assemblies = SystemHelper.LoadAppAssemblies(); builder.RegisterAssemblyTypesWithLiftTimeScope(assemblies).AsImplementedInterfaces().AsSelf(); //注册WCF的契约 //builder.RegisterWCFContract(assemblies, m => m.Location.EndsWith(".Service.Interface.dll", StringComparison.CurrentCultureIgnoreCase)); //注册ModelBinders builder.RegisterModelBinders(typeof(Int32ListModelBinder).Assembly); builder.RegisterModelBinderProvider(); //注册Controllers builder.RegisterControllers(assemblies, m => m.Location.EndsWith(".Web.dll", StringComparison.CurrentCultureIgnoreCase)); //注册路由 builder.RegisterInstance(RouteTable.Routes).As <RouteCollection>(); //注册GlobalFilters builder.RegisterInstance(GlobalFilters.Filters).As <GlobalFilterCollection>(); //注册ModelBinders builder.RegisterInstance(ModelBinders.Binders); #region ////注册缓存 //builder.RegisterType<DefaultCacheProvider>().Named<ICacheProvider>("aspnet").AsSelf().SingleInstance(); //builder.RegisterType<AppFabricCacheProvider>().Named<ICacheProvider>("appfabric").AsSelf().SingleInstance(); ////注册日志 //builder.RegisterLogger(); #endregion } catch (Exception ex) { throw; } }
private static void Main(string[] args) { var env = new ApplicationEnvironment(); var bootupConfigurationProvider = new BootupConfigurationProvider(env); Autofac.ContainerBuilder cb = new Autofac.ContainerBuilder(); cb.RegisterInstance <IEnvironment>(env); cb.RegisterInstance(bootupConfigurationProvider).As <IBootupConfigurationProvider>(); cb.RegisterModule <Teleware.Foundation.Core.Module>(); cb.RegisterModule <Teleware.Foundation.Configuration.Module>(); cb.RegisterModule <Teleware.Foundation.Diagnostics.Loggers.NLog.Module>(); cb.RegisterModule <Teleware.Foundation.Data.Memory.Module>(); //cb.RegisterModule<Teleware.Foundation.Data.EntityFramework.Module>(); //cb.RegisterModule<Teleware.Foundation.Data.EntityFramework.Oracle.Module>(); var container = cb.Build(); using (var lt = container.BeginLifetimeScope()) { var logger = lt.Resolve <ILogger <Test> >(); logger.Warn(1, "warn"); //logger.Debug(2, new ArgumentException("arg"), "debug"); //var loggerFactory = lt.Resolve<ILoggerFactory>(); //var logger2 = loggerFactory.CreateLogger("manual"); //logger2.Fatal(0, "death"); //var uow = lt.Resolve<IUnitOfWork>(); //var repo = lt.Resolve<ICRUDRepository<Test>>(); //var test = new Test(); //repo.Add(test); //var item0 = repo.Query().FirstOrDefault(); //test.Foo = "a"; //repo.Update(test); //var item = repo.Query().FirstOrDefault(); //repo.Remove(test); //uow.Commit(); } }
private void RegisterPluginModuleServices(Autofac.ContainerBuilder builder) { var modulesWithServices = _application.AllPluginModules.OfType <IPluginModuleService>(); foreach (IPluginModuleService moduleService in modulesWithServices) { var moduleServiceType = moduleService.GetType(); var moduleServiceInterfaces = moduleServiceType.GetInterfacesDerivedFrom <IPluginModuleService>(); builder.RegisterInstance(moduleService) .As(moduleServiceInterfaces.ToArray()) .SingleInstance(); } }
internal Shell CreateShell(BrowseForRepositoryEvent browseForRepositoryEvent, Arguments arguments) { var builder = new Autofac.ContainerBuilder(); ChorusUIComponentsInjector.Inject(builder, _projectPath, SyncUIFeatures.Advanced); builder.RegisterInstance(browseForRepositoryEvent).As <BrowseForRepositoryEvent>().SingleInstance(); //For now, we like the idea of just using the login name. But //this allows someone to override that in the ini (which would be for all users of this machine, then) builder.Register <IChorusUser>(c => new ChorusUser(c.Resolve <HgRepository>().GetUserNameFromIni(new NullProgress(), System.Environment.UserName))); builder.RegisterType <Shell>(); if (arguments != null) { builder.RegisterInstance(arguments); Synchronizer.s_testingDoNotPush = arguments.DontPush; //hack, at this point it would take a lot of plumbing //to get this properly to any synchronizer that is created. Can be fixed if/when we go to the //autofac generated factor approach } _container = builder.Build(); var shell = _container.Resolve <Shell>(); var system = new ChorusSystem(_projectPath); system.Init(string.Empty); shell.AddPage("Review", system.WinForms.CreateHistoryPage()); shell.AddPage("Notes", system.WinForms.CreateNotesBrowser()); shell.AddPage("Send/Receive", _container.Resolve <SyncPanel>()); shell.AddPage("Settings", _container.Resolve <SettingsView>()); shell.AddPage("Troubleshooting", _container.Resolve <TroubleshootingView>()); return(shell); }
public void TestMethodTick() { try { int time = 1; var builder = new Autofac.ContainerBuilder(); builder.RegisterType(typeof(DefaultCommandContext)).As(typeof(ICommandContext)).SingleInstance(); builder.RegisterType(typeof(DefaultEventContext)).As(typeof(IEventContext)).SingleInstance(); builder.RegisterType(typeof(InprocEventProviderCommandBus)).As(typeof(ICommandBus)).SingleInstance(); builder.RegisterType(typeof(DefaultCommandContext)).As(typeof(ICommandContext)).SingleInstance(); builder.RegisterType(typeof(EmptyCommandStreamStorager)).As(typeof(ICommandStreamStorager)).SingleInstance(); builder.RegisterInstance(new MQEventStorager((IMessageProducer)null)).As <IEventStorager>().SingleInstance(); builder.RegisterType(typeof(EmptyServiceLocator)).As <IServiceLocator>().SingleInstance(); builder.RegisterType(typeof(EmptyServiceRegister)).As <IServiceRegister>().SingleInstance(); //this.ServiceRegister.RegisterType<MyJsonSer, IJsonSerializer>(string.Empty, Never.IoC.ComponentLifeStyle.Singleton); Console.WriteLine(string.Format("进行{0}次计算,目标是构建ICommandBus", time.ToString("N2"))); using (var container = builder.Build()) { using (var t = new Utils.MethodTickCount((x) => { Console.WriteLine(x); })) { for (var i = 0; i < time; i++) { var res = container.Resolve <ICommandBus>(); } } } using (var t = new Utils.MethodTickCount((x) => { Console.WriteLine(x); })) { for (var i = 0; i < time; i++) { var res = this.Resolve <ICommandBus>(); } } } catch (Exception ex) { Console.WriteLine(ex); } finally { this.Release(); } }
private void InitializeContainer() { var builder = new Autofac.ContainerBuilder(); builder.RegisterType <AddStrokesUndoItem>().As <IAddStrokesUndoItem>(); builder.RegisterType <DrawingMode>().As <IDrawingMode>(); builder.RegisterType <DrawingPageViewModel>().As <IDrawingPageViewModel>(); builder.RegisterType <ErasingMode>().As <IErasingMode>(); builder.RegisterType <EraseStrokesUndoItem>().As <IEraseStrokesUndoItem>(); builder.RegisterType <PanningMode>().As <IPanningMode>(); builder.RegisterType <SplitPage>().As <ISplitPage>(); builder.RegisterType <CarouselPage>().As <ICarouselPage>(); builder.RegisterType <SplitPageViewModel>().As <ISplitPageViewModel>(); builder.RegisterInstance(_undoManager).As <IUndoManager>(); Container = builder.Build(); }