Example #1
0
        public static void RegistAll()
        {
            var iocBuilder = new Autofac.ContainerBuilder();

            iocBuilder.RegisterControllers(Assembly.GetExecutingAssembly());
            iocBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            //Type baseType = typeof(IH2FBase);
            var iInterfaces = Assembly.Load("H2F.TEST.Interface");
            var implement   = Assembly.Load("H2F.TEST.Implement");

            iocBuilder.RegisterAssemblyTypes(iInterfaces, implement).AsImplementedInterfaces();

            iocBuilder.RegisterType <Student>().As <IPerson>();
            iocBuilder.RegisterType <Worker>().Keyed <IPerson>(PersonType.Worker);

            iocBuilder.RegisterType <Student>().Keyed <IPerson>(PersonType.Student);


            iocBuilder.RegisterType <Log4net>().As <ILogger>();
            var config = GlobalConfiguration.Configuration;

            iocBuilder.RegisterWebApiFilterProvider(config);
            IContainer iocContainer = iocBuilder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(iocContainer);
            System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(iocContainer));

            IocContainerManager.SetContanier(iocContainer);
        }
        private static void SetAutofacContainer(string dbConnectionString)
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<DefaultValidationBus>().As<IValidationBus>().InstancePerHttpRequest();
            builder.RegisterAssemblyTypes(Assembly.Load("Utilities")).AsImplementedInterfaces().InstancePerHttpRequest();

            builder.RegisterType<ScrabbleClubContext>().WithParameter("connectionStringName", dbConnectionString).InstancePerHttpRequest();

            var infrastructureDataAccessLayerAssembly = Assembly.Load("DataAccess");
            builder.RegisterAssemblyTypes(infrastructureDataAccessLayerAssembly)
                   .Where(t => t.Name.EndsWith("Repository"))
                   .AsImplementedInterfaces().InstancePerHttpRequest();

            var domainLayerAssembly = Assembly.Load("Domain");
            builder.RegisterAssemblyTypes(domainLayerAssembly)
                   .Where(t => t.Name.EndsWith("Service"))
                   .AsImplementedInterfaces()
                   .InstancePerHttpRequest();

            var applicationLayerAssembly = Assembly.Load("Application");
            builder.RegisterAssemblyTypes(applicationLayerAssembly)
                   .AsClosedTypesOf(typeof (IValidationHandler<>)).InstancePerHttpRequest();
            builder.RegisterAssemblyTypes(applicationLayerAssembly)
                   .Where(t => t.Name.EndsWith("Service"))
                   .AsImplementedInterfaces()
                   .InstancePerHttpRequest();

            builder.RegisterFilterProvider();
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            builder.RegisterType<ShippingByWeightService>().As<IShippingByWeightService>().InstancePerHttpRequest();

            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new ShippingByWeightObjectContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>("nop_object_context_shipping_weight_zip")
                    .InstancePerHttpRequest();

                builder.Register<ShippingByWeightObjectContext>(c => new ShippingByWeightObjectContext(dataProviderSettings.DataConnectionString))
                    .InstancePerHttpRequest();
            }
            else
            {
                //register named context
                builder.Register<IDbContext>(c => new ShippingByWeightObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>("nop_object_context_shipping_weight_zip")
                    .InstancePerHttpRequest();

                builder.Register<ShippingByWeightObjectContext>(c => new ShippingByWeightObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerHttpRequest();
            }

            //override required repository with our custom context
            builder.RegisterType<EfRepository<ShippingByWeightRecord>>()
                .As<IRepository<ShippingByWeightRecord>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_shipping_weight_zip"))
                .InstancePerHttpRequest();
        }
 protected override void Load(Autofac.ContainerBuilder builder)
 {
     builder.RegisterType <RabbitMQOptions>().AsSelf();
     builder.RegisterType <ConnectionPool>().AsSelf().SingleInstance();
     builder.RegisterType <RabbitBaseQueue>().AsSelf().SingleInstance();
     builder.RegisterType <RabbitMQConsumerClientFactory>().AsSelf().SingleInstance();
 }
Example #5
0
        static void Main(string[] args)
        {
            var containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterType<Cpu>().As<ICpu>().SingleInstance();
            containerBuilder.RegisterType<Emulator>().As<IEmulator>();
            containerBuilder.RegisterType<Memory>().As<IMemory>().SingleInstance();
            containerBuilder.RegisterType<Ppu>().As<IPpu>();

            var instructionTypes = Assembly.GetExecutingAssembly().GetTypes().Where(f => typeof(IInstruction).IsAssignableFrom(f) && !f.IsAbstract).ToArray();

            containerBuilder.RegisterTypes(instructionTypes)
                .As<IInstruction>();

            var container = containerBuilder.Build();

            var emulator = container.Resolve<IEmulator>();
            var memory = container.Resolve<IMemory>();
            memory.SetCartridge(new Cartridge("../../roms/nestest.nes"));
            emulator.Reset();
            for (;;)
            {
                emulator.Step();
            }
        }
Example #6
0
        public static void Run()
        {
            var builder = new Autofac.ContainerBuilder();
            var config = GlobalConfiguration.Configuration;
            var service = builder.RegisterType<FormularioService>()
                .As<IFormularioService>();

            var factory = builder.RegisterType<DatabaseFactoryFormulario>()
                .As<IDatabaseFactory>();

            var unit = builder.RegisterType<UnitOfWorkGeneric>()
                .As<IUnitOfWOrkGeneric<IDatabaseFactory>>();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterWebApiFilterProvider(config);

            builder.RegisterWebApiModelBinderProvider();

            service.InstancePerRequest();
            factory.InstancePerRequest();
            unit.InstancePerRequest();


            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            config.Formatters.Remove(config.Formatters.XmlFormatter);

            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
Example #7
0
        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));
            }
        }
        private static void SetIocContainer()
        {
            //Implement Autofac

            var configuration = GlobalConfiguration.Configuration;
            var builder = new ContainerBuilder();

            // Register MVC controllers using assembly scanning.
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            // Register MVC controller and API controller dependencies per request.
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerDependency();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerLifetimeScope();

            // Register service
            builder.RegisterAssemblyTypes(typeof(ProfileService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces().InstancePerDependency();

            // Register repository
            builder.RegisterAssemblyTypes(typeof(ProfileRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerDependency();

            var container = builder.Build();

            //for MVC Controller Set the dependency resolver implementation.
            var resolverMvc = new AutofacDependencyResolver(container);
            System.Web.Mvc.DependencyResolver.SetResolver(resolverMvc);
        }
Example #9
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ConfigManager>().As<IConfigManager>()
                .WithParameter(new NamedParameter("navigation", this.Navigation));

            builder.RegisterType<SecurityManager>().As<ISecurityManager>();
        }
Example #10
0
        /// <summary>
        /// Override to add registrations to the container.
        /// </summary>
        /// <remarks>
        /// Note that the ContainerBuilder parameter is unique to this module.
        /// </remarks>
        /// <param name="builder">The builder through which components can be
        ///             registered.</param>
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterModule<WebWorkContextModule>();
            builder.RegisterType<DefaultHttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();

            builder.RegisterType<ShellRoute>().InstancePerDependency();
        }
Example #11
0
 /// <summary>
 /// 加载配置
 /// </summary>
 /// <param name="builder">容器生成器</param>
 protected override void Load( ContainerBuilder builder ) {
     base.Load( builder );
     //builder.RegisterInstance( new Context() ); -----该方法也可
     builder.RegisterType<Context>().InstancePerLifetimeScope();
     builder.RegisterType<Operation3>().As<IOperation3>();
     builder.RegisterType<Operation4>().As<IOperation4>();
 }
Example #12
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterModule(new RepositoryModule());

            builder.RegisterType(typeof(SampleArchContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
            builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerRequest();
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ViewFactory>().As<IViewFactory>().SingleInstance();
            builder.RegisterType<Navigator>().As<INavigator>().SingleInstance();
            builder.Register<INavigation>(ctx => App.Current.MainPage.Navigation).SingleInstance();

        }
Example #14
0
        public static Autofac.ContainerBuilder AddTransactionProcessingServices(this Autofac.ContainerBuilder services)
        {
            services.RegisterType <LockService>()
            .As <ILockService>()
            .WithParameter("connectionString", ConfigurationManager.ConnectionStrings["DB"].ConnectionString);

            services.RegisterType <TransactionTriggers.TransactionTriggerWorker>()
            .Keyed <IWorker>("TransactionTriggerWorker")
            .InstancePerDependency();

            services.RegisterType <TransactionTriggers.TransactionTriggerPool>()
            .Keyed <IWorkerPool>("TransactionTrigger")
            .WithParameter("threadCount", 1)
            .WithParameter("timeOut", TimeSpan.FromSeconds(5))
            .SingleInstance();

            //services.RegisterType<SSBQueueManager>()
            //    .Keyed<IQueueManager>("TransactionTriggerQueue")
            //    .WithParameter("connectionString", ConfigurationManager.ConnectionStrings["DB"].ConnectionString)
            //    .WithParameter("queueName", "QTransactionTrigger")
            //    .WithParameter("receiveService", "RX_TransactionTrigger")
            //    .SingleInstance();

            services.RegisterType <MemoryQueue>()
            .Keyed <IQueueManager>("TransactionTriggerQueue")
            .SingleInstance();

            return(services);
        }
Example #15
0
        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>();
            }
        }
        private static IContainer CreateContainer(string projectFilePath)
        {
            ContainerBuilder builder = new ContainerBuilder();

            // Features
            RegisterFeatures(builder);

            // Services
            builder.RegisterType<FileSystemService>().As<IFileSystemService>().SingleInstance();
            builder.RegisterType<ProjectService>()
                .As<IProjectService>()
                .WithParameter("projectFilePath", projectFilePath)
                .SingleInstance();

            // View Models
            builder.RegisterType<MainViewModel>().As<IMainViewModel>().SingleInstance();

            // Views
            builder.RegisterType<MainView>()
                .As<IMainView>()
                .PropertiesAutowired(PropertyWiringOptions.None)
                .SingleInstance();

            return builder.Build();
        }
        public TripleTexFacade(int syncSystem, string syncPassword, string username, string password)
        {
            _syncSystem = syncSystem;
            _syncPassword = syncPassword;
            _username = username;
            _password = password;

            // Setup IoC and DI
            var builder = new ContainerBuilder();

            // The JsonService keeps the session cookie and has to have one instance per lifetime
            builder.RegisterType<JsonService>().As<IJsonService>().InstancePerLifetimeScope();

            //builder.RegisterAssemblyTypes()
            //       .Where(r => r.Name.EndsWith("Service"))
            //       .AsImplementedInterfaces();

            builder.RegisterType<SyncService>().As<ISyncService>();
            builder.RegisterType<CompanyService>().As<ICompanyService>();
            builder.RegisterType<OrderService>().As<IOrderService>();
            builder.RegisterType<ProductService>().As<IProductService>();

            _container = builder.Build();

            // Login
            _container.Resolve<ISyncService>().Login(_syncSystem, _syncPassword, _username, _password);
        }
Example #18
0
        public Bootstrapper()
        {
            IContainer container = null;

            var builder = new ContainerBuilder();

            builder.RegisterModule(new AgathaClientModule
                                   {
                                       ContainerFactory = () => container,
                                       RequestResponseAssembly = typeof (Nitrogen.Common.AssemblyHook).Assembly
                                   });

            builder.RegisterModule(new Log4NetModule {SectionName = "CommonLogging.Nitrogen.Client"});

            builder.RegisterType<MessageStream>().As<IMessageStream>().SingleInstance();

            builder.RegisterType<ShellViewModel>().AsSelf();

            builder.RegisterModule(new WPFModule());
            builder.RegisterType<WPFStartable>().AsSelf();

            builder.RegisterType<ClientStartable>().AsSelf();

            // DataExplorer
            builder.RegisterModule(new DataExplorerModule());
            builder.RegisterType<DataExplorerStartable>().AsSelf();

            // Build the container
            container = builder.Build();

            // TODO : Ideally change this, so it isn't resolved like this
            container.Resolve<WPFStartable>().Start();
            container.Resolve<ClientStartable>().Start();
            container.Resolve<DataExplorerStartable>().Start();
        }
Example #19
0
        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);
        }
Example #20
0
        protected override void Load(Autofac.ContainerBuilder builder)
        {
            builder.RegisterType <RestApplication>().As <RestApplication, IRestApplication>();
            builder.RegisterType <SoapApplication>().As <SoapApplication, ISoapApplication>();
            builder.RegisterType <CommandConverter>().As <ICommandConverter>();

            SetupExtensibility(builder);
            if (WithDatabase)
            {
                SetupPostgres(builder);
            }
            SetupPatterns(builder);
            SetupSerialization(builder);

            builder.RegisterType <RepositoryAuthentication>().As <IAuthentication <SecureString>, IAuthentication <string>, IAuthentication <byte[]> >();
            builder.RegisterType <RepositoryPrincipalFactory>().As <IPrincipalFactory>();
            builder.RegisterType <PermissionManager>().As <IPermissionManager>().SingleInstance();

            builder.RegisterType <LogFactory>().As <ILogFactory>().SingleInstance();
            builder.RegisterType <NLogLogger>().As <ILogger>();

            builder.RegisterType(typeof(ProcessingEngine)).As(typeof(IProcessingEngine)).SingleInstance();

            builder.RegisterType <OnContainerBuild>().As <IStartable>();

            base.Load(builder);
        }
Example #21
0
        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));
            }
        }
Example #22
0
 public void Register(Autofac.ContainerBuilder builder, SmartConfig config)
 {
     builder.RegisterGeneric(typeof(ITmpl <>)).As(typeof(IT <>)).InstancePerLifetimeScope();
     builder.RegisterGeneric(typeof(ITmpl <,>)).As(typeof(IT <,>)).InstancePerLifetimeScope();
     builder.RegisterType <TestClass>().AsSelf().PropertiesAutowired().SingleInstance();
     builder.RegisterType <TestClass2>().AsSelf().PropertiesAutowired().SingleInstance();
 }
Example #23
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Register: create and configure the container
            _container = BootstrapContainer();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));

            var builder = new ContainerBuilder();

            //var configurationRepository =
            //    new ConfigurationRepository.ConfigurationRepository() as IConfigurationRepository;

            //builder.Register(c => configurationRepository).As<IConfigurationRepository>().SingleInstance();

            builder.RegisterType<StashCoreApiConsumer>().As<IStashCoreApiConsumer>();

            builder.RegisterType<PullTrackerRepository>().As<IPullTrackerRepository>();

            builder.RegisterType<RequestProcessFacade>().As<IRequestProcessFacade>();

            IContainer localContainer = builder.Build();

            AutofacHelper.Scope = localContainer;

            _containerProvider = new ContainerProvider(localContainer);
        }
Example #24
0
        // ConfigureContainer is where you can register things directly
        // with Autofac. This runs after ConfigureServices so the things
        // here will override registrations made in ConfigureServices.
        // Don't build the container; that gets done for you by the factory.
        // ReSharper disable once UnusedMember.Global
        public void ConfigureContainer(Autofac.ContainerBuilder builder)
        {
            // Register your own things directly with Autofac here. Don't
            // call builder.Populate(), that happens in AutofacServiceProviderFactory
            // for you.
            builder.RegisterType <AkkaGameService>()
            .As <IGameService>()
            .SingleInstance();


            var connectionString = Configuration.GetSection("ConnectionString").Value;

            builder.RegisterType <CoreWarsDataContext>()
            .WithParameter("connectionString", connectionString)
            .As <CoreWarsDataContext>()
            .AsImplementedInterfaces();

            builder.RegisterType <AggregatedCompetitorFactory>();

            builder
            .RegisterType <SelectMaxRandomCollectionSelectionStrategy <IActorRef> >()
            .AsImplementedInterfaces();

            builder.RegisterType <PlayerSet <IActorRef> >()
            .AsImplementedInterfaces();

            builder.RegisterModule <PythonScriptingModule>();
            builder.RegisterModule <DilemmaModule>();
            builder.RegisterModule <TicTacToeModule>();
        }
Example #25
0
        /// <summary>
        /// Configures the multitenant dependency container.
        /// </summary>
        private static IContainer ConfigureDependencies()
        {
            // Register default dependencies in the application container.
            var builder = new ContainerBuilder();
            builder.RegisterType<Consumer>().As<IDependencyConsumer>().InstancePerDependency();
            builder.RegisterType<BaseDependency>().As<IDependency>().SingleInstance();
            var appContainer = builder.Build();

            // Create the multitenant container.
            var mtc = new MultitenantContainer(_tenantIdentifier, appContainer);

            // Configure overrides for tenant 1. Tenant 1 registers their dependencies
            // as instance-per-dependency.
            mtc.ConfigureTenant('1', b => b.RegisterType<Tenant1Dependency>().As<IDependency>().InstancePerDependency());

            // Configure overrides for tenant 2. Tenant 2 registers their dependencies
            // as singletons.
            mtc.ConfigureTenant('2', b => b.RegisterType<Tenant2Dependency>().As<IDependency>().SingleInstance());

            // Configure overrides for the default tenant. That means the default
            // tenant will have some different dependencies than other unconfigured
            // tenants.
            mtc.ConfigureTenant(null, b => b.RegisterType<DefaultTenantDependency>().As<IDependency>().SingleInstance());

            return mtc;
        }
Example #26
0
        private void configureIoC()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            builder.Register(ctx => LogManager.GetLogger("trace"))
                .As<Logger>()
                .InstancePerHttpRequest();

            builder.RegisterType<ProcessRunner>()
                .AsImplementedInterfaces()
                .InstancePerDependency()
                ;

            builder.RegisterType<DotProcessor>()
                .AsImplementedInterfaces()
                .SingleInstance()
                ;

            builder.RegisterType<Ansi2HtmlConverter>()
                .AsImplementedInterfaces()
                .InstancePerDependency()
                ;

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Example #27
0
 public void Init() {
     var builder = new ContainerBuilder();
     builder.RegisterType<TokenManager>().As<ITokenManager>();
     builder.RegisterType<TestTokenProvider>().As<ITokenProvider>();
     _container = builder.Build();
     _tokenManager = _container.Resolve<ITokenManager>();
 }
		public static void RegisterHandlersWithAutofac(ContainerBuilder containerBuilder, IReadOnlyCollection<MessageRegistration> registrations)
		{
			var handlers = registrations.Select(x => x.Handler).Distinct();
			var piplelineHandlers = registrations.Select(x => x.Pipeline).Distinct().SelectMany(x => x).Distinct();

			RegisterLeafHandlers(containerBuilder, handlers);
			RegisterPipelineHandlers(containerBuilder, piplelineHandlers);

			foreach (var registration in registrations)
			{
				if (registration.Dependancies.Any())
				{
					foreach (var dependancy in registration.Dependancies)
					{
						containerBuilder.RegisterType(dependancy).AsSelf();
					}
				}

				if (registration.ScopedDependancies.Any())
				{
					foreach (var dependancy in registration.ScopedDependancies)
					{
						containerBuilder.RegisterType(dependancy).AsSelf().AsImplementedInterfaces().InstancePerLifetimeScope();
					}
				}
			}
		}
Example #29
0
        private static IContainer RegisterServices(ContainerBuilder builder)
        {
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // EF PSMContext
            builder.RegisterType<PSMContext>()
                   .As<DbContext>()
                   .InstancePerRequest();

            builder.RegisterType<DbFactory>()
               .As<IDbFactory>()
               .InstancePerRequest();

            builder.RegisterType<UnitOfWork>()
                .As<IUnitOfWork>()
                .InstancePerRequest();

            builder.RegisterGeneric(typeof(EntityBaseRepository<>))
                   .As(typeof(IEntityBaseRepository<>))
                   .InstancePerRequest();

            Container = builder.Build();

            return Container;
        }
        private static void ConfigureAutofac(HttpConfiguration config, IIssueStore issueStore)
        {
            var builder = new ContainerBuilder();

            if (issueStore == null)
            {
                builder.RegisterType<InMemoryIssueStore>()
                    .As<IIssueStore>()
                    .InstancePerLifetimeScope();

            }
            else
            {
                builder.RegisterInstance(issueStore);
            }

            builder.RegisterType<IssueStateFactory>()
                .As<IStateFactory<Issue, IssueState>>()
                .InstancePerLifetimeScope();

            builder.RegisterType<IssueLinkFactory>()
                .InstancePerLifetimeScope();

            builder.RegisterHttpRequestMessage(config);
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            var container = builder.Build();

            var resolver =
                new AutofacWebApiDependencyResolver(container);

            config.DependencyResolver = resolver;
        }
Example #31
0
        public void RegisterDefaultServices()
        {
            var builder = new ContainerBuilder();
            builder.RegisterInstance(container);
            builder.RegisterType<AutofacServiceLocator>()
                .As<IServiceLocator>()
                .SingleInstance();
            builder.RegisterAssemblyTypes(typeof(IServiceBus).Assembly)
                .AssignableTo<IBusConfigurationAware>()
                .As<IBusConfigurationAware>()
                .SingleInstance();
            builder.RegisterType<DefaultReflection>()
                .As<IReflection>()
                .SingleInstance();
            builder.RegisterType(config.SerializerType)
                .As<IMessageSerializer>()
                .SingleInstance();
            builder.RegisterType<EndpointRouter>()
                .As<IEndpointRouter>()
                .SingleInstance();
            foreach(var module in config.MessageModules)
            {
                builder.RegisterType(module)
                    .Named<string>(module.FullName)
                    .As(typeof(IMessageModule))
                    .SingleInstance();
            }
            builder.Update(container);

            foreach(var busConfigurationAware in container.Resolve<IEnumerable<IBusConfigurationAware>>())
                busConfigurationAware.Configure(config, this);
        }
        /// <summary>
        /// Registers the modules type bindings
        /// </summary>
        /// <param name="builder">
        /// The container builder.
        /// </param>
        protected override void Load(ContainerBuilder builder)
        {
            // Resource locator
            builder.RegisterType<DocsResourceLocatorConfig>()
                .As<IResourceLocatorConfig>()
                .Named<IResourceLocatorConfig>("docs");

            // Fields Configuration
            builder.RegisterType<DocsFieldInfoConfig>()
                .As<IDocsFieldInfoConfig>()
                .Named<IDocsFieldInfoConfig>("docs");

            // Content Types Configuration
            builder.RegisterType<DocsContentTypeInfoConfig>()
                .As<IDocsContentTypeInfoConfig>()
                .Named<IDocsContentTypeInfoConfig>("docs");

            // Lists Configuration
            builder.RegisterType<DocsListInfoConfig>()
                .As<IDocsListInfoConfig>()
                .Named<IDocsListInfoConfig>("docs");

            // Image Renditions
            builder.RegisterType<DocsImageRenditionInfoConfig>()
                .As<IDocsImageRenditionInfoConfig>()
                .Named<IDocsImageRenditionInfoConfig>("docs");
        }
Example #33
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                "DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});

            var builder = new ContainerBuilder();

            // Register Web API controller in executing assembly.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // Register a logger service to be used by the controller and middleware.
            builder.Register(c => new Logger()).As<ILogger>().InstancePerRequest();

            // Autofac will add middleware to IAppBuilder in the order registered.
            // The middleware will execute in the order added to IAppBuilder.
            builder.RegisterType<FirstMiddleware>().InstancePerRequest();
            builder.RegisterType<SecondMiddleware>().InstancePerRequest();

            var container = builder.Build();

            // Create and assign a dependency resolver for Web API to use.
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            // This should be the first middleware added to the IAppBuilder.
            app.UseAutofacMiddleware(container);

            // Make sure the Autofac lifetime scope is passed to Web API.
            app.UseAutofacWebApi(config);

            app.UseWebApi(config);
        }
        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>();
        }
Example #35
0
 public void Register(ContainerBuilder builder, SmartConfig config)
 {
     builder.RegisterType<Context.SampleDbContext>().As<DbContext>().InstancePerLifetimeScope();
     builder.RegisterType<Context.OtherDbContext>().As<Context.IOtherDbContext>().InstancePerLifetimeScope();
     builder.RegisterGeneric(typeof(EFRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
     builder.RegisterGeneric(typeof(EFRepository<,>)).As(typeof(IRepository<,>)).InstancePerLifetimeScope();
 }
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            Singleton<IDependencyResolver>.Instance = new DependencyResolver();

            string collectionString = "Data Source=.;Initial Catalog=demo;User ID=sa;Password=sa;Trusted_Connection=False;";
            builder.Register<IDbContext>(c => new WaterMoonContext(collectionString)).PerLifeStyle(ComponentLifeStyle.LifetimeScope);
            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).PerLifeStyle(ComponentLifeStyle.LifetimeScope);
            builder.RegisterGeneric(typeof(PagedList<>)).As(typeof(IPagedList<>)).PerLifeStyle(ComponentLifeStyle.LifetimeScope);

            builder.RegisterType<DefualtMapping>().As<IMapping>().SingleInstance();

            //注册所有实现IConsumer<>类型的对象
            var consumers = typeFinder.FindClassesOfType(typeof(IConsumer<>)).ToList();
            foreach (var consumer in consumers)
            {
                builder.RegisterType(consumer)
                    .As(consumer.FindInterfaces((type, criteria) =>
                    {
                        var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                        return isMatch;
                    }, typeof(IConsumer<>)))
                    .PerLifeStyle(ComponentLifeStyle.LifetimeScope);
            }
            builder.RegisterType<EventPublisher>().As<IEventPublisher>().SingleInstance();
            builder.RegisterType<SubscriptionService>().As<ISubscriptionService>().SingleInstance();

            builder.RegisterType<DemoService>().As<IDemoService>().PerLifeStyle(ComponentLifeStyle.LifetimeScope);
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ServicioDatosImpl>().As<IServicioDatos>().SingleInstance();
            builder.RegisterType<Session>().SingleInstance();

            builder.RegisterType<Login>();
            builder.RegisterType<Principal>();
            builder.RegisterType<Registro>();
            builder.RegisterType<NuevoBlocView>();
            builder.RegisterType<LoginViewModel>();
            builder.RegisterType<PrincipalViewModel>();
            builder.RegisterType<RegistroViewModel>();
            builder.RegisterType<NuevoBlocViewModel>();
            

            //Registrar la instancia de una funcion que va a devolver una pagina
            builder.RegisterInstance<Func<Page>>(() =>
            {
                //saber que pagina está en primer plano (pagina principalen este momento) y le digo que me lo de como una pagina maestrodetalle
                var masterP = App.Current.MainPage as MasterDetailPage;
                //si no se puede convertir como masterdetailpage me das el mainpage
                var page = masterP != null ? masterP.Detail : App.Current.MainPage;
                //creo objeto navigation de tipo pagina
                var navigation = page as IPageContainer<Page>;
                //devuelvo la pagina actual o la maestra (le pregunto al objeto si es la pagina principal)
                return navigation != null ? navigation.CurrentPage : page;
            });
        }
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.RegisterType<ApplicationDatabase>()
                .As<IApplicationDatabase>()
                .SingleInstance();

            builder
                .RegisterType<DatabaseUpgradeDetector>()
                .As<IDatabaseUpgradeDetector>()
                .SingleInstance();

            builder
                .RegisterType<SqlDatabaseProvider>()
                .As<IDatabaseProvider>()
                .Named<IDatabaseProvider>("sql")
                .WithMetadata<IDatabaseProviderMetadata>(c => c.For(m => m.Name, "Sql"));

            builder
                .RegisterType<SqlCeDatabaseProvider>()
                .As<IDatabaseProvider>()
                .Named<IDatabaseProvider>("sqlce")
                .WithMetadata<IDatabaseProviderMetadata>(c => c.For(m => m.Name, "SqlCe"));
        }
        private static IContainer RegisterServices(ContainerBuilder builder)
        {

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // EF DbContext
            builder.RegisterType<EntitiesContext>()
                   .As<DbContext>()
                   .InstancePerApiRequest();

            // Register repositories by using Autofac's OpenGenerics feature
            // More info: http://code.google.com/p/autofac/wiki/OpenGenerics
            builder.RegisterGeneric(typeof(EntityRepository<>))
                   .As(typeof(IEntityRepository<>))
                   .InstancePerApiRequest();

            // Services
            builder.RegisterType<CryptoService>()
                .As<ICryptoService>()
                .InstancePerApiRequest();

            builder.RegisterType<MembershipService>()
                .As<IMembershipService>()
                .InstancePerApiRequest();

            builder.RegisterType<ShipmentService>()
                .As<IShipmentService>()
                .InstancePerApiRequest();

            return builder.Build();
        }
        private void RegisterServices(ContainerBuilder builder)
        {
            // repositories
            //override required repository with our custom context
            builder.RegisterType<EfRepository<GroupRule>>()
                .As<IRepository<GroupRule>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(TAX_GROUPS_CONTEXT_NAME))
                .InstancePerLifetimeScope();

            // repositories
            //override required repository with our custom context
            builder.RegisterType<EfRepository<TaxClass>>()
                .As<IRepository<TaxClass>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(TAX_GROUPS_CONTEXT_NAME))
                .InstancePerLifetimeScope();

            // repositories
            //override required repository with our custom context
            builder.RegisterType<EfRepository<MemberGroup>>()
                .As<IRepository<MemberGroup>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(TAX_GROUPS_CONTEXT_NAME))
                .InstancePerLifetimeScope();

            // repositories
            //override required repository with our custom context
            builder.RegisterType<EfRepository<TaxRule>>()
                .As<IRepository<TaxRule>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(TAX_GROUPS_CONTEXT_NAME))
                .InstancePerLifetimeScope();
            ///////////////////////////////////////////////////////////////////////////////////////////////

            // services
            //builder.RegisterType<GroupDealService>().As<IGroupDealService>().InstancePerLifetimeScope();
            ///////////////////////////////////////////////////////////////////////////////////////////////
        }
 protected override void Load(ContainerBuilder builder)
 {
     builder.RegisterType<VendingMachineDbContext>()
         .As<DbContext>()
         .AsSelf()
         .InstancePerLifetimeScope();
     builder.RegisterGeneric(typeof (EntityFrameworkUnitOfWork<>))
         .As(typeof (UnitOfWork<>))
         .InstancePerDependency();
     builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
         .Where(x => x.IsClosedTypeOf(typeof (IEntityFactory<,>)))
         .AsImplementedInterfaces()
         .InstancePerDependency();
     builder.RegisterType<CoinsRefundedEventCommitter>()
         .As(typeof (EntityFrameworkTrackedEventCommitter<UserVendingMachineAggregationEntity, CoinsRefundedEvent>))
         .InstancePerDependency();
     builder.RegisterType<GoodsBuyedEventCommitter>()
         .As(typeof (EntityFrameworkTrackedEventCommitter<UserVendingMachineAggregationEntity, GoodsBuyedEvent>))
         .InstancePerDependency();
     //builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
     //    .Where(x => x.IsClosedTypeOf(typeof (ITrackedEventCommitter<,>)))
     //    .As(typeof(EntityFrameworkTrackedEventCommitter<,>))
     //    .AsImplementedInterfaces()
     //    .InstancePerDependency();
 }
        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();
        }
Example #43
0
        public static void Launch()
        {
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterType <Tasks.TaskException>();
            builder.RegisterType <Tasks.TaskSyncLineShiftPerfLastShift>();
            builder.RegisterType <Tasks.TaskOEEActionManagement>();
            builder.RegisterType <UnitOfWork>()
            .As <IUnitOfWork>()
            .InstancePerBackgroundJob();

            builder.RegisterType <DatabaseFactory>()
            .As <IDatabaseFactory>()
            .InstancePerBackgroundJob();

            builder.RegisterAssemblyTypes(typeof(SystemFunctionRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces()
            .InstancePerBackgroundJob();

            builder.RegisterAssemblyTypes(typeof(SystemService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .InstancePerBackgroundJob();

            Hangfire.GlobalConfiguration.Configuration.UseAutofacActivator(builder.Build());
        }
Example #44
0
 public ContainerBuilderHelper()
 {
     Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();
     builder.RegisterType<LS.Cores.SysLogsService>().As<LS.Cores.ISysLogs>();
     builder.RegisterType<LS.Cores.SysMenuService>().As<LS.Cores.ISysMenu>();
     builder.RegisterType<LS.Cores.SysDictionaryService>().As<LS.Cores.ISysDictionary>();
     container = builder.Build();
 }
        private static void RegisterDependencies(Autofac.ContainerBuilder builder)
        {
            builder.RegisterType <ConfigProvider>().AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <WordsCalculator>().AsImplementedInterfaces().InstancePerDependency();
            builder.RegisterType <FormattedOutputBuilder>().AsImplementedInterfaces();

            RegisterInputProviders(builder);
        }
Example #46
0
 public void Build()
 {
     Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();
     builder.RegisterType <DatabaseHandler>().As <IDatabaseHandler>().SingleInstance();
     builder.RegisterType <AuthentificationManager>().As <IAuthentificationManager>().SingleInstance();
     builder.RegisterType <KickTaskConnection>().SingleInstance();
     Container = builder.Build();
 }
 protected override void Register(Autofac.ContainerBuilder builder)
 {
     builder.RegisterType <PlacementFileParser>().As <IPlacementFileParser>();
     builder.RegisterType <StubCacheManager>().As <ICacheManager>();
     builder.RegisterType <StubParallelCacheContext>().As <IParallelCacheContext>();
     builder.RegisterType <InMemoryWebSiteFolder>().As <IWebSiteFolder>()
     .As <InMemoryWebSiteFolder>().InstancePerLifetimeScope();
 }
 public IContainer CreateContainer()
 {
     var builder = new Autofac.ContainerBuilder();
     builder.RegisterType<MyCommandHandler>().As<ICommandHandler<AnotherCommand>>();
     builder.RegisterType<MyCommandHandler>().As<ICommandHandler<MyCommand>>();
     builder.RegisterGeneric(typeof(CompositeCommandHandler<>)).As(typeof(ICommandHandler<>));
     return builder.Build();
 }
        /// <summary>
        /// 注册实例类型(type)
        /// 【RegisterType】
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        protected override Autofac.ContainerBuilder RegisterFunc(Autofac.ContainerBuilder builder)
        {
            builder.RegisterType <StudentRepository>();
            builder.RegisterType <StudentAppService>();

            //除了泛型,还可以传入type
            //builder.RegisterType(typeof(StudentService));
            //builder.RegisterType(typeof(StudentRepository));
            return(builder);
        }
        public static Autofac.ContainerBuilder AddSearchIndexerServices(this Autofac.ContainerBuilder services)
        {
            services.RegisterType <IndexQueue>().As <IIndexQueue>().SingleInstance();
            services.RegisterType <IndexWorker>().As <IIndexWorker>().SingleInstance();
            services.RegisterType <IndexRegister>().As <IIndexRegister>().SingleInstance();
            services.RegisterType <IndexStore>().As <IIndexStore>().InstancePerDependency();
            services.RegisterType <SearchService>().As <ISearchService>().InstancePerDependency();

            return(services);
        }
Example #51
0
        public static Autofac.ContainerBuilder AddDomainServices(this Autofac.ContainerBuilder services)
        {
            services.RegisterType <HR1Context>().As <IHR1Context>().InstancePerDependency();

            services.RegisterType <AccountingEntitySetupManager>().As <IAccountingEntitySetupManager>().InstancePerDependency();

            //services.RegisterType<SequenceNumberGeneator>().As<ISequenceNumberGeneator>().InstancePerDependency();

            return(services);
        }
        /// <summary>
        /// 注册实例类型(type)和服务类型(interface)
        /// 【RegisterType】+【As】
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        protected override Autofac.ContainerBuilder RegisterFunc(Autofac.ContainerBuilder builder)
        {
            builder.RegisterType <StudentRepository>() //指定实例类型
            .As <IStudentRepository>();                //指定服务类型

            builder.RegisterType(typeof(StudentAppService))
            .As(typeof(IStudentAppService))
            .AsSelf()
            .AsImplementedInterfaces();    //以其实现的所有接口作为服务类型
            return(builder);
        }
Example #53
0
        /// <summary>
        /// 命名实例注册
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        protected override Autofac.ContainerBuilder RegisterFunc(Autofac.ContainerBuilder builder)
        {
            builder.RegisterType <MyService>()
            .As <IMyService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <MyOtherService>()
            .Named <IMyService>("other")
            .InstancePerLifetimeScope();
            return(builder);
        }
Example #54
0
        /// <summary>
        /// 属性注入方法2
        /// 【RegisterType】+【PropertiesAutowired】
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        protected override Autofac.ContainerBuilder RegisterFunc(Autofac.ContainerBuilder builder)
        {
            builder.RegisterType <TeacherRepository>()
            .AsImplementedInterfaces();

            builder.RegisterType <TeacherAppService>()
            .PropertiesAutowired()
            .AsImplementedInterfaces();

            return(builder);
        }
Example #55
0
        static App()
        {
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterType <LoginUser>().AsSelf().SingleInstance();
            builder.RegisterType <RootData>().AsSelf().SingleInstance();

            var container = builder.Build();

            LifetimeScope = container.BeginLifetimeScope(typeof(App).ToString());
        }
Example #56
0
 protected override void Load(Autofac.ContainerBuilder builder)
 {
     builder.RegisterType <PostgresDataAccessObjectService>().As <IDataAccessObjectService>();
     builder.RegisterType <WebObjectService>().As <IWebObjectService>();
     builder.Register(c =>
                      new BranchOfficeDbContext()
                      ).As <BranchOfficeDbContext>().SingleInstance();
     builder.RegisterType <ConfigurationService>().As <IConfigurationService>();
     builder.RegisterType <HQAPIClient>().As <IHQAPIClient>();
     builder.RegisterType <SynchronizatorService>().
     As <ISynchronizatorService>().SingleInstance();
 }
Example #57
0
        static void Aop()
        {
            Autofac.ContainerBuilder containerBuilder = new Autofac.ContainerBuilder();
            containerBuilder.RegisterType <PrintTimeHandler>();
            containerBuilder.RegisterType <DaoImpl>().As <Dao>().InterceptedBy(typeof(PrintTimeHandler)).EnableClassInterceptors();
            var life = containerBuilder.Build().BeginLifetimeScope();
            var dao  = life.Resolve <Dao>();

            dao.insert();
            dao.update();
            dao.delete();
        }
Example #58
0
 /// <summary>
 /// Registers the comm service.
 /// </summary>
 /// <param name="builder">The builder.</param>
 protected static void RegisterCommService(Autofac.ContainerBuilder builder)
 {
     //comm service
     builder.RegisterType <iPow.Infrastructure.Crosscutting.Comm.Service.CityInfoService>()
     .As <iPow.Infrastructure.Crosscutting.Comm.Service.ICityInfoService>().InstancePerHttpRequest();
     builder.RegisterType <iPow.Infrastructure.Crosscutting.Comm.Service.DiscountService>()
     .As <iPow.Infrastructure.Crosscutting.Comm.Service.IDiscountService>().InstancePerHttpRequest();
     builder.RegisterType <iPow.Infrastructure.Crosscutting.Comm.Service.LocationService>()
     .As <iPow.Infrastructure.Crosscutting.Comm.Service.ILocationService>().InstancePerHttpRequest();
     builder.RegisterType <iPow.Infrastructure.Crosscutting.Comm.Service.SightInfoSearchService>()
     .As <iPow.Infrastructure.Crosscutting.Comm.Service.ISightInfoSearchService>().InstancePerHttpRequest();
 }
Example #59
0
        private IServiceProvider ConfigAutofacDI(IServiceCollection services)
        {
            var builder = new Autofac.ContainerBuilder();

            builder.RegisterType <RequestIdFactory>().As <IRequestIdFactory>().SingleInstance();
            builder.RegisterType <RequestId>().As <IRequestId>();

            builder.Populate(services);
            this.ApplicationContainer = builder.Build();

            return(new AutofacServiceProvider(this.ApplicationContainer));
        }
Example #60
0
        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>();
        }