当前位置: 首页>>代码示例>>C#>>正文


C# ContainerBuilder.RegisterModule方法代码示例

本文整理汇总了C#中Autofac.ContainerBuilder.RegisterModule方法的典型用法代码示例。如果您正苦于以下问题:C# ContainerBuilder.RegisterModule方法的具体用法?C# ContainerBuilder.RegisterModule怎么用?C# ContainerBuilder.RegisterModule使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Autofac.ContainerBuilder的用法示例。


在下文中一共展示了ContainerBuilder.RegisterModule方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Application_Start

        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(@"../../../log4net.xml"));

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ContainerBuilder builder = new ContainerBuilder();

            builder.RegisterModule(new BusConfigModule());

            // use raven
            builder.RegisterModule(new RavenConfigModule());

            // or use nhibernate
            // builder.RegisterModule(new NHibernateConfigModule());

            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            containerProvider = new ContainerProvider(builder.Build());

            DependencyResolver.SetResolver(new AutofacDependencyResolver(containerProvider.ApplicationContainer));
        }
开发者ID:james-wu,项目名称:CQRSEventSourcingSample,代码行数:25,代码来源:Global.asax.cs

示例2: Setup

        public static void Setup()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            // Register for API Controllers
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterFilterProvider();
            builder.RegisterModelBinderProvider();
            builder.RegisterModule<AutofacWebTypesModule>();

            // Find all autofac modules and include them.
            builder.RegisterModule<IdentityModule>();

            // Find all IStartable tasks and register them.
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            builder.RegisterAssemblyTypes(assemblies)
                .AssignableTo<IStartable>()
                .As<IStartable>()
                .SingleInstance();

            // Enable property injection into action filters (including authorize attribute).
            builder.RegisterFilterProvider();

            IContainer container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
开发者ID:vietplayfuri,项目名称:Asp_Master,代码行数:29,代码来源:DependancyInjectionConfig.cs

示例3: Application_Start

        protected void Application_Start(object sender, EventArgs e)
        {
            var builder = new ContainerBuilder();

            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<AuthenticationService>().As<IAuthenticationService>();
            builder.RegisterModule<AutofacWebTypesModule>();
            builder.RegisterModule<NHibernateModule>();

            // Change controller action parameter injection by changing web.config.
            builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>().InstancePerHttpRequest();

            // MVC integration test items
            builder.RegisterType<InvokerDependency>().As<IInvokerDependency>();

            // DomainServices
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AssignableTo<DomainService>();
            builder.RegisterModule<AutofacDomainServiceModule>();

            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            DomainService.Factory = new AutofacDomainServiceFactory(new MvcContainerProvider());

            RegisterRoutes(RouteTable.Routes);
        }
开发者ID:yuleyule66,项目名称:autofac,代码行数:27,代码来源:Global.asax.cs

示例4: CreateContainer

        /// <summary>
        /// Creates the DI container for the application.
        /// </summary>
        /// <param name="context">The application context that controls when the application will terminate.</param>
        /// <param name="storageDirectory">The directory in which all the uploaded files are stored.</param>
        /// <returns>The DI container.</returns>
        public static IContainer CreateContainer(ApplicationContext context, string storageDirectory)
        {
            var builder = new ContainerBuilder();
            {
                builder.RegisterInstance(context)
                    .As<ApplicationContext>()
                    .ExternallyOwned()
                    .SingleInstance();

                builder.RegisterModule(new UtilitiesModule());
                builder.RegisterModule(
                    new CommunicationModule(
                        new List<CommunicationSubject>
                            {
                                CommunicationSubjects.TestTransfer,
                                CommunicationSubjects.TestExecution,
                            },
                        new List<ChannelType>
                            {
                                ChannelType.NamedPipe,
                                ChannelType.TcpIP,
                            },
                        true));

                RegisterFileSystem(builder);
                RegisterReports(builder);
                RegisterInformation(builder);
                RegisterNotifications(builder);
                RegisterCommands(builder, storageDirectory);
            }

            return builder.Build();
        }
开发者ID:pvandervelde,项目名称:Sherlock,代码行数:39,代码来源:DependencyInjection.cs

示例5: InMemory_Request_Retrieve_Mock_Test

        public void InMemory_Request_Retrieve_Mock_Test()
        {
            var builder = new ContainerBuilder();

            builder.RegisterModule<ProcessingConsumerModule>();
            builder.RegisterModule<BillingConsumerModule>();
            builder.RegisterModule<UserManagementConsumerModule>();

            var itemList = new List<Item>();
            itemList.Add(new Item { Info = "mockResponse" });
            var mockItemRepository = new Mock<IRepository<Item>>();

            mockItemRepository.Setup(rep =>
                rep.Query(It.IsAny<Expression<Func<Item, bool>>>()))
                   .Returns(itemList.AsQueryable());
            builder.Register(c =>
                mockItemRepository.Object).As<IRepository<Item>>();

            using (var service = Service.InMemory(builder).Start())
            {
                var msg = new RequestItemMessage("mockSelection");
                var client = service.CreateRequestClient<RequestItem, ItemResponse>();
                var response = client.Request(msg).Result;
                Assert.AreEqual("mockResponse", response.ItemInfo);
            }
        }
开发者ID:gmich,项目名称:SOA,代码行数:26,代码来源:ServiceBusRequestResponseTests.cs

示例6: BuildContainer

        private IContainer BuildContainer()
        {
            // Use 'InstancePerLifetimeScope' to create instance which will be shared during the consuming of one message

            var builder = new ContainerBuilder();

            builder.RegisterModule(new ServiceBusModule());
            builder.RegisterModule(new TranslationServiceModule());
            builder.RegisterModule(new MailerModule());

            // Register razor mail message factory (have not found a way to put this in a module, due to the dependencyResolver parameter)
            builder.RegisterType<RazorMailMessageFactory>()
                .WithParameter(new NamedParameter("templateResolver", new DefaultTemplateResolver("Infrastructure", "TemplateMailMessages")))
                .WithParameter(new NamedParameter("templateBase", typeof(ViewBaseClass<>)))
                .WithParameter(new NamedParameter("dependencyResolver", new Func<Type, object>(x => _container.Resolve(x))))
                .WithParameter(new NamedParameter("templateCache", new InMemoryTemplateCache()))
                .As<IRazorMailMessageFactory>()
                .InstancePerLifetimeScope();

            builder.Register(c => NHibernateHelper.SessionFactory).SingleInstance();
            builder.Register(c => c.Resolve<ISessionFactory>().OpenSession()).As<ISession>().InstancePerLifetimeScope();
            builder.RegisterType<InMemoryKeyValueCache>().As<IKeyValueCache>().InstancePerLifetimeScope();
            builder.RegisterType<TranslationRepository>().As<ITranslationRepository>().InstancePerLifetimeScope();
            builder.RegisterType<ApplicationSettings>().As<IApplicationSettings>().SingleInstance();
            builder.RegisterType<NLogLogger>().As<ILogger>().InstancePerLifetimeScope();

            return builder.Build();
        }
开发者ID:robinvanderknaap,项目名称:SkaeleArchitecture,代码行数:28,代码来源:MailSenderService.cs

示例7: Initialize

        public static IContainer Initialize(ContainerBuilder builder, HttpConfiguration config)
        {
            // Register all controllers
            builder.RegisterApiControllers(typeof(Startup).Assembly);

            // Register Autofac filter provider
            builder.RegisterWebApiFilterProvider(config);

            // Register model binders
            builder.RegisterWebApiModelBinderProvider();

            // Register all Autofac specific IModule implementations
            builder.RegisterAssemblyModules(typeof(Startup).Assembly);
            builder.RegisterAssemblyModules(typeof(AutofacMediator).Assembly);

            builder.RegisterModule(new RequestHandlerModule());
            builder.RegisterModule(new EntityFrameworkModule());
            builder.RegisterModule(new DocumentGeneratorModule());

            // http://www.talksharp.com/configuring-autofac-to-work-with-the-aspnet-identity-framework-in-mvc-5
            builder.RegisterType<IwsIdentityContext>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<ApplicationUserManager>().As<UserManager<ApplicationUser>>().InstancePerRequest();

            return builder.Build();
        }
开发者ID:EnvironmentAgency,项目名称:prsd-iws,代码行数:27,代码来源:AutofacBootstrapper.cs

示例8: Load

 protected override void Load(ContainerBuilder builder)
 {
     builder.RegisterModule(new LogModule());
     builder.RegisterModule(new SecurityModule());
     builder.Register(c => new GZipFilter()).Keyed<IMessageFilter>(ZipMode.GZip).SingleInstance();
     builder.Register(c => new RSACryptoFilter()).Keyed<IMessageFilter>(CryptoMode.RSA).SingleInstance();
     builder.Register(c => new Crc32Filter()).Keyed<IMessageFilter>(ChecksumMode.Crc32).SingleInstance();
     builder.Register(c => new MessageFilterFactory()).AsSelf().SingleInstance();
     builder.Register(c => new Json()).Keyed<ISerializer>(SerializeMode.Json).SingleInstance();
     builder.Register(c => new Protobuf()).Keyed<ISerializer>(SerializeMode.Protobuf).SingleInstance();
     builder.Register(c => new ExceptionCounterFilter()).AsSelf().SingleInstance();
     builder.Register(c => new CommandHandler(c.Resolve<TimeoutNotifyProducerConsumer<AbstractAsyncCommand>>())).AsSelf().SingleInstance();
     builder.Register(c => new DuplexMessageWriterImplV1()).Keyed<IMessageWriter<DuplexMessage>>(MessageVersion.V1).SingleInstance();
     builder.Register(c => new DuplexMessageReaderImplV1()).Keyed<IMessageReader<DuplexMessage>>(MessageVersion.V1).SingleInstance();
     builder.RegisterType<TimeoutNotifyProducerConsumer<AbstractAsyncCommand>>()
         .WithParameter(new NamedParameter("capacity", AbstractAsyncCommand.BLOCK_UNTIL_TIMEOUT_QUEUE_CAPACITY))
         .AsSelf()
         .SingleInstance()
         .OnActivated(o =>
         {
             o.Instance.OnConsume += (sender, e) =>
             {
                 var consumingItem = e.ConsumingItem as ChunkedConsumingItem<AbstractAsyncCommand>;
                 if (consumingItem == null) return;
                 foreach (var item in consumingItem.Chunk)
                 {
                     try
                     {
                         item.RunAsync();
                     }
                     catch (Exception) { }
                 }
             };
         });
 }
开发者ID:zesus19,项目名称:c5.v1,代码行数:35,代码来源:RpcNetModule.cs

示例9: SetupContainer

        private static void SetupContainer()
        {
            ContainerBuilder builder = new ContainerBuilder();

            builder.RegisterType<Logger>().As<ILogger>();

            builder.RegisterType<AutofacServiceProvider>()
                .As<Xdore.Core.IServiceProvider>()
                .InstancePerLifetimeScope();

            #region Modules

            builder.RegisterModule<AutofacWebTypesModule>();
            builder.RegisterModule<DataAccessRegistrationModule>();
            builder.RegisterModule<ServicesRegistrationModule>();

            #endregion

            builder.RegisterControllers(Assembly.GetExecutingAssembly())
                .PropertiesAutowired();

            builder.RegisterFilterProvider();

            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            ServiceLocator.Initialize(() =>
            {
                return DependencyResolver.Current.GetService<IServiceProvider>();
            });

            IDbContextFactory dbFactory = DependencyResolver.Current.GetService<IDbContextFactory>();
            dbFactory.InitDbContext();
        }
开发者ID:CBSAdvisor,项目名称:Xdore,代码行数:34,代码来源:AppConfig.cs

示例10: Setup

        public static void Setup()
        {
            var builder = new ContainerBuilder();

            // Register controllers
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // Register modules
            builder.RegisterModule(new ServiceBusModule());
            builder.RegisterModule(new NHibernateSessionModule());
            builder.RegisterModule(new TranslationServiceModule());
            builder.RegisterModule(new LoggerModule());

            // Register types
            builder.RegisterType<ApplicationSettings>().As<IApplicationSettings>().SingleInstance();
            builder.RegisterType<InMemoryKeyValueCache>().As<IKeyValueCache>().SingleInstance();
            builder.RegisterType<TranslationRepository>().As<ITranslationRepository>();
            builder.RegisterType<UserRepository>().As<IUserRepository>();
            builder.RegisterType<LogRepository>().As<ILogRepository>();
            builder.RegisterType<DefaultEncryptor>().As<IEncryptor>();
            builder.RegisterType<CultureService>().As<ICultureService>();
            builder.Register(c => new RegularExpressionPasswordPolicy(c.Resolve<IApplicationSettings>().PasswordPolicy)).As<IPasswordPolicy>();

            Container = builder.Build();

            // Enables autofac to resolve controllers instead of default asp.net mvc implementation
            DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
        }
开发者ID:robinvanderknaap,项目名称:SkaeleArchitecture,代码行数:28,代码来源:AutoFac.cs

示例11: Application_Start

        protected void Application_Start()
        {
            SessionScope.SetSessionScopeService(new WebSessionScopeService());
            RequestScope.SetRequestScopeService(new WebRequestScopeService());

            var builder = new ContainerBuilder();

            builder.RegisterModule<ServiceModule>();
            builder.RegisterModule<DomainModule>();
            builder.RegisterModule<QueryModelModule>();

            builder.Register(a => new AutofacDependencyResolver(() => CurrentLifetimeScope, DependencyResolver.Current))
                   .As<IDependencyResolver>()
                   .SingleInstance();

            builder.RegisterType<AutofacControllerFactory>().As<IControllerFactory>().SingleInstance();

            builder.RegisterType<DotLessCompiler>().AsSelf().SingleInstance();

            RegisterComponents(builder);

            _container = builder.Build();

            CurrentLifetimeScope = _container.BeginLifetimeScope();

            DependencyResolver.SetResolver(_container.Resolve<IDependencyResolver>());

            RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            RouteTable.Routes.MapRoute("Login", "login", new { controller = "account", action = "login" });

            RouteTable.Routes.MapRoute("Default", "{controller}/{action}/{id}",
                                       new {controller = "Dashboard", action = "Index",
                                       id = UrlParameter.Optional});
        }
开发者ID:wingertge,项目名称:test,代码行数:35,代码来源:Application.cs

示例12: Load

        protected override void Load(ContainerBuilder builder)
        {
            // Specific registrations and initialization:
            Plugins.SetInitializationLogging(DeploymentUtility.InitializationLogProvider);

            if (_deploymentTime)
            {
                builder.RegisterModule(new DatabaseGeneratorModuleConfiguration(_shortTransaction));
                builder.RegisterType<DataMigration>();
                builder.RegisterType<DatabaseCleaner>();
                builder.RegisterType<ApplicationGenerator>();
                Plugins.FindAndRegisterPlugins<IGenerator>(builder);
            }
            else
            {
                builder.RegisterType<ApplicationInitialization>();
                Plugins.FindAndRegisterPlugins<IServerInitializer>(builder);
            }

            // General registrations:
            builder.RegisterModule(new Rhetos.Configuration.Autofac.DefaultAutofacConfiguration(_deploymentTime, _deployDatabaseOnly));

            // Specific registrations override:
            builder.RegisterType<ProcessUserInfo>().As<IUserInfo>();
            builder.RegisterInstance(DeploymentUtility.InitializationLogProvider).As<ILogProvider>(); // InitializationLogProvider allows overriding deployment logging (both within and outside IoC).

            base.Load(builder);
        }
开发者ID:davorpr1,项目名称:Rhetos,代码行数:28,代码来源:AutofacModuleConfiguration.cs

示例13: Application_Start

        void Application_Start(object sender, EventArgs e)
        {
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
            GlobalConfiguration.Configure(WebApiConfig.Register);
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            BaseFrontendMappings.Initialize();

            InitializerModule.InitializeDb();

            AddTask("RemoveUsers", 3600);

            var config = GlobalConfiguration.Configuration;

            //Autofac Configuration
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModule(new MapperModule());
            builder.RegisterModule(new RepositoryModule());
            builder.RegisterModule(new ContractModule());
            builder.RegisterModule(new EfModule());
            builder.RegisterModule(new BaseFrontendModule());

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
开发者ID:TomKaminski,项目名称:ITAD2015,代码行数:32,代码来源:Global.asax.cs

示例14: verify_usage_across_multiple_registration_modules

        public void verify_usage_across_multiple_registration_modules()
        {
            var module1 = new SimplePipelineModule(item =>
            {
                item.RegisterPipeline<MultipipelineTests.In, MultipipelineTests.Out>()
                    .Bind<MultipipelineTests.InOutTranslator>();

                item.RegisterPipeline<string, int, string>("foo")
                    .Bind(p => (p * 3).ToString());

            });

            var module2 = new SimplePipelineModule(item => item.RegisterPipeline<int, string>()
                                                               .Bind(p => (p * 2).ToString()));

            var builder = new ContainerBuilder();
            builder.RegisterModule(module1);
            builder.RegisterModule(module2);

            var ctx = builder.Build();

            var value1 = ctx.Resolve<Functor<MultipipelineTests.In, MultipipelineTests.Out>>()(new MultipipelineTests.In()).NewValue;
            var value2 = ctx.Resolve<Functor<int, string>>()(10);
            var value3 = ctx.Resolve<Functor<string, int, string>>()("foo", 10);

            Assert.That(value1, Is.EqualTo(20));
            Assert.That(value2, Is.EqualTo("20"));
            Assert.That(value3, Is.EqualTo("30"));
        }
开发者ID:stevehebert,项目名称:wormhole,代码行数:29,代码来源:MultipleRegisrationTests.cs

示例15: RegisterModules

 private static IContainer RegisterModules()
 {
     var builder = new ContainerBuilder();
     builder.RegisterModule<WebApi>();
     builder.RegisterModule<ServiceArchCore>();
     return builder.Build();
 }
开发者ID:bUKaneer,项目名称:ServiceArch,代码行数:7,代码来源:AutofacConfig.cs


注:本文中的Autofac.ContainerBuilder.RegisterModule方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。